以多对多关系symfony2的形式设置multiple ='false' [英] set multiple='false' in a form in a many to many relation symfony2

查看:68
本文介绍了以多对多关系symfony2的形式设置multiple ='false'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在两个实体A和B之间存在多对多关系.

I have a many-to-many relationship between two entities A and B.

因此,在添加表单时,为了将entityA添加到entityB,我正在执行以下操作:

So when adding a form, in order to add entityA to entityB, I am doing the following:

$builder          
    ->add('entityAs', 'entity', array(
      'class'    => 'xxxBundle:EntityA',
      'property' => 'name',
      'multiple' => true,
    ));}

一切都很好.

但是根据entityA的字段类型,有时我想将'multiple'设置为false,所以我要执行以下操作:

But depending on the field type of entityA, I want to sometimes set 'multiple' to false, so I'm doing the following :

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,

        ));
}

这给了我以下错误:

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 

有人可以帮助我吗?

推荐答案

在EntityA中,您有类似的东西,对吧?

In EntityA, you have something like this, right?

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

这篇关于以多对多关系symfony2的形式设置multiple ='false'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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