Is there any way an entity field can be shown grouped in option groups in symfony2 (v.2.1), for example I have something like this in my form class:
$builder->add('account',
'entity',
array(
'class' => 'MyBundle\Entity\Account',
'query_builder' => function(EntityRepository $repo){
return $repo->findAllAccounts();
},
'required' => true,
'empty_value' => 'Choose_an_account',
);
But (of course) they are displayed as the repository class reads it from the db and I would like to display them grouped in the combobox. This post mentions that featured added to the 2.2 release out of the box, but what options do we 2.1 users have?
The Grouping would be based on a field called Type
, lets say I have a getter for that called getType()
in my Account entity that returns a string.
Thanks.
I did a similar thing when handling with categories.
First, when you build the form, pass the list of choices as a result from a function
getAccountList()
as follows:The function should do something like follows (the content depend on the way you structure your result).
Of course, you can do it more dynamics! Mine is just a brief example!
You also have to pass the
EntityManager
to your custom form class. So, define the constructor:And pass the
EntityManager
when you initiate theMyAccountType
object.