[英]set multiple='false' in a form in a many to many relation symfony2
I have a many-to-many relationship between two entities A and B. 我在两个实体A和B之间建立了多对多关系。
So when adding a form, in order to add entityA
to entityB
, I am doing the following: 因此,在添加表单时,为了将entityA
添加到entityB
,我正在执行以下操作:
$builder
->add('entityAs', 'entity', array(
'class' => 'xxxBundle:EntityA',
'property' => 'name',
'multiple' => true,
));}
And everything is alright. 一切都很好。
But depending on the field type of entityA, I want to sometimes set 'multiple' to false, so I'm doing the following : 但是,根据entityA的字段类型,有时我想将“ multiple”设置为false,因此我正在执行以下操作:
if($type=='a'){
$builder
->add('entityAs', 'entity', array(
'class' => 'xxxBundle:entityA',
'property' => 'name',
'multiple' => true,
));}
else {
$builder
->add('entityAs', 'entity', array(
'class' => 'xxxBundle:entityA',
'property' => 'name',
'multiple' => false,
));
}
This gives me the following error: 这给了我以下错误:
Catchable Fatal Error: Argument 1 passed to Doctrine\Common\Collections\ArrayCollection::__construct() must be an array, object given, called in C:\wamp\www\Symfony\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php on line 519 and defined in C:\wamp\www\Symfony\vendor\doctrine\common\lib\Doctrine\Common\Collections\ArrayCollection.php line 48
Can anybody help me? 有谁能够帮助我?
In EntityA, you have something like this, right? 在EntityA中,您有类似这样的东西,对吗?
public function setEntitiesB($data)
{
$this->entitiesB = $data ;
}
Now because you can also receive single value instead of array of values, you need something like this: 现在,由于您还可以接收单个值而不是值的数组,因此需要这样的操作:
public function setEntitiesB($data)
{
if ( is_array($data) ) {
$this->entitiesB = $data ;
} else {
$this->entitiesB->clear() ;
$this->entitiesB->add($data) ;
}
}
i would check the entityA value in the controller and depending on it create different forms. 我会检查控制器中的entityA值,并根据它创建不同的形式。
in controller: 在控制器中:
if ($entityA->getType() == 'a') {
$form = new FormB(); // form with multiple true
} else {
$form = new FormA(); // form with multiple false
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.