该问题与this one类似,但是存在巨大差异:我没有固定数量的要添加的元素。Symfony 2.3.6。嵌套形式
下面是窗体的预览以及窗体的外观。我有一个用户实体的表格,其中包括不同的应用实体,每个应用实体有几个用户组实体。
用户
class User extends BaseUser
{
...
/**
* @ORM\ManyToMany(targetEntity="Application", inversedBy="users")
* @ORM\JoinTable(name="users_applications")
*/
protected $applications;
/**
* @ORM\ManyToMany(targetEntity="UserGroup", inversedBy="users")
* @ORM\JoinTable(name="users_groups")
*/
protected $user_groups;
应用
class Application
{
...
/**
* @ORM\ManyToMany(targetEntity="User", mappedBy="applications")
*/
protected $users;
/**
* @ORM\OneToMany(targetEntity="UserGroup", mappedBy="application")
*/
protected $user_groups;
用户组
class UserGroup
{
...
/**
* @ORM\ManyToOne(targetEntity="Application", inversedBy="user_groups")
* @ORM\JoinColumn(name="application_id", referencedColumnName="id")
*/
protected $application;
/**
* @ORM\ManyToMany(targetEntity="User", mappedBy="user_groups")
*/
protected $users;
UserFormType
class UserFormType extends AbstractType
{
// Array of applications is generated in the Controller and passed over by the constructor
private $applications;
public function buildForm(FormBuilderInterface $builder, array $options)
{
...
if ($this->applications && count($this->applications) > 0)
{
foreach ($this->applications AS $application)
{
$builder->add('applications', 'entity', array
(
'class' => 'MyBundle:Application',
'property' => 'title',
'query_builder' => function(EntityRepository $er) use ($application)
{
return $er->createQueryBuilder('a')
->where('a.id = :id')
->setParameter('id', $application->getId());
},
'expanded' => true,
'multiple' => true
));
$builder->add('user_groups', 'entity', array
(
'class' => 'MyBundle:UserGroup',
'property' => 'title',
'query_builder' => function(EntityRepository $er) use ($application)
{
return $er->createQueryBuilder('ug')
->where('ug.application = :application')
->setParameter('application', $application);
},
'expanded' => true,
'multiple' => true
));
}
}
...
问题:我已经设法包括应用和用户组实体,但由于应用实体通过加入formbuilder循环中,实体被覆盖,使得多个应用程序只有一个应用程序被渲染。
我们对嵌套表单有一些类似的设置,但我们使用集合,也许它可以成为您的问题的解决方案! http://symfony.com/doc/current/cookbook/form/form_collections.html – acrobat
您在每次迭代中添加相同的字段(名称应用程序)。这是不可能的。我建议为实体子类型创建特殊类型 – zulus