Symfony2 form widgets for many-to-many relations

点点圈 提交于 2019-12-09 10:45:41

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/10581177/symfony2-form-widgets-for-many-to-many-relations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!