Symfony2 form widgets for many-to-many relations

放肆的年华 提交于 2019-12-03 13:38:52

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.

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