In Symfony 1 there was as form widget named admin_double_list. It generated two select fields named Unassociated and Associated. It also generated buttons to add items from one list to another.
Is there any easy way to accomplish this in Symfony2? Or maybe some other user friendly way to edit many-to-many relations?
In the documentation there are only four widgets for many-to-many relations and none of them are very nice when there are massive amount of relation possibilities to edit.
You can easily manage many-to-many relationships with entity form field. For example If User
as a many-to-many relationship with Group
, you can simply add to the builder:
$builder->add('groups', 'entity', array(
'multiple' => true, // Multiple selection allowed
'expanded' => true, // Render as checkboxes
'property' => 'name', // Assuming that the entity has a "name" property
'class' => 'Acme\HelloBundle\Entity\Group',
);
This will generate a checkbox list where associated entities are marked (checked) while unassociated are not. Setting expanded
to false
you can render it as a select element (multiple one).
If you need to customize the way that groups are retrieved you can also pass a query_builder
option, either QueryBuilder
instance or a closure where $er
is the EntityRepository
'query_builder' => function(\Doctrine\ORM\EntityRepository $er) {
$qb = $er->createQueryBuilder('g');
return $qb->orderBy('g.name', 'DESC);
}
For more complex scenario look also at collection form type, but you have to deal with jQuery/Javascript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With