N
N
Nikolai Egorov2018-06-28 20:44:47
symfony
Nikolai Egorov, 2018-06-28 20:44:47

How to correctly process a form that is not associated with an Entity?

Made the form not related to the entity. In fact, this is a simple form of sorting records in the admin panel (in the future I will add filtering by parameters).

class ImageFilterType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('sortBy', ChoiceType::class, [
                'choices' => [
                    'ID' => 'id',
                    'label.createdAt' => 'createdAt',
                    'label.publishedAt' => 'publishedAt',
                    'label.updatedAt' => 'updatedAt',
                ],
                'label' => 'label.sort_by',
                'required' => true,
            ])
            ->add('direction', ChoiceType::class, [
                'choices' => [
                    'label.sort_direction_ASC' => 'ASC',
                    'label.sort_direction_DESC' => 'DESC'
                ],
                'label' => 'label.sort_direction',
                'required' => true,
            ])
            ->add('submit', SubmitType::class, [
                'label' => 'OK'
            ]);
    }
}

In the controller, I'm trying to get the parameters passed by the form:
/**
     * @Route("/images/{page}", defaults={"page": 1}, name="admin_image_list")
     */
    public function index(int $page, Request $request, ImageRepository $imageRepository): Response
    {
        $sortBy = $request->get('sortBy', 'id');
        $direction = $request->get('direction', 'DESC');

        $filterForm = $this->createForm(ImageFilterType::class, [
            'sortBy' => $sortBy,
            'direction' => $direction,
        ])->handleRequest($request);

        $images = $imageRepository->findEntities([], $sortBy, $direction, $page, 10);

        return $this->render('admin/gallery/image_list.html.twig', [
            'images' => $images,
            'filterForm' => $filterForm->createView(),
        ]);
    }

But in the end, I don't get the `$sortBy` and `$direction` parameters in the controller - they are assigned by default. In the debug panel, you can see that I get not separate `sortBy` and `direction` parameters, but an array
image_filter [▼
  "sortBy" => "updatedAt"
  "direction" => "DESC"
  "submit" => ""
  "_token" => "dOketsGIJFAVlVaPvjbBtzx5b3ksQ8nZ6jwY-JT7HDo"
]

If the form is submitted by the GET method, then the address line is: ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BoShurik, 2018-06-28
@nickicool

$filter = $filterForm->getData();
$images = $imageRepository->findEntities([], $filter['sortBy'], $filter['direction'], $page, 10);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question