Symfony2表单小部件,用于多对多关系 [英] Symfony2 form widgets for many-to-many relations

查看:80
本文介绍了Symfony2表单小部件,用于多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Symfony 1中,有一个名为admin_double_list的表单小部件.它生成了两个名为Unassociated和Associated的选择字段.它还生成了用于将项目从一个列表添加到另一个列表的按钮.

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.

在Symfony2中,有没有简单的方法可以做到这一点?还是其他一些用户友好的方式来编辑多对多关系?

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',
);

这将生成一个复选框列表,其中已标记(选中)关联的实体,而未关联的则未标记.将expanded设置为false可以将其呈现为选择元素(多个).

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).

如果您需要自定义组的检索方式,则还可以传递query_builder选项(QueryBuilder实例或$erEntityRepository

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);
}

有关更复杂的情况,请参见收藏表格类型 ,但是您必须处理jQuery/Javascript.

For more complex scenario look also at collection form type, but you have to deal with jQuery/Javascript.

这篇关于Symfony2表单小部件,用于多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆