Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 form widgets for many-to-many relations

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.

like image 564
teemup Avatar asked May 14 '12 10:05

teemup


Video Answer


1 Answers

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.

like image 111
gremo Avatar answered Sep 22 '22 17:09

gremo