这个问题类似于这个,但有一个巨大的区别:我没有固定数量的要添加的元素。
以下是表单预览以及其应该看起来的样子。我有一个用户实体的表单,其中包含不同的应用程序实体,每个应用程序实体都有几个用户组实体。
用户
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
));
}
}
...
问题: 我已经成功地包含了应用程序和用户组实体,但由于应用程序实体是通过循环添加到表单构建器中的,所以实体被覆盖,这样拥有多个应用程序时只有一个应用程序被呈现。