該問題與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