Search code examples
phpsymfonydoctrinesymfony4

Symfony 4 Forms: implementing per-Entity custom sorting in QueryBuilder for ChoiceType fields


I seem to have some troubles getting my head around the intrinsics of the Symfony (4) Form component.

I want to:

a) store information per-Entity(Repository?) on how the default sort order should be, like $entityRepository->sortOrder = ['default' => ['LastName ASC', 'FirstName ASC'], 'custom1' => [...]];

b) use that information to instruct the Form to use that ordering with the query_builder option/attribute for the ChoiceType form field

So the question is, how/where should i ideally store that information and how should i feed this to the Form object / QueryBuilder?

Pointing me in a direction doing it in a "industry-standard" fashion would be greatly appreciated.


Solution

  • Symfony Forms comes with an EntityType that allows you to specify a custom query:

    https://symfony.com/doc/4.4/reference/forms/types/entity.html#ref-form-entity-query-builder

    If the ordering is specific to the form, you might want to build the query inline in your form (like in the example of the link above). If the same ordering of an entity applies to multiple forms, extract it into a method in your repository and use the method when building the custom query in the form type.