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

查看:21
本文介绍了以多对多关系 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 DoctrineCommonCollectionsArrayCollection::__construct() must be an array, object given, called in C:wampwwwSymfonyvendordoctrineormlibDoctrineORMUnitOfWork.php on line 519 and defined in C:wampwwwSymfonyvendordoctrinecommonlibDoctrineCommonCollectionsArrayCollection.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天全站免登陆