【问题标题】:set multiple='false' in a form in a many to many relation symfony2以多对多关系 symfony2 的形式设置 multiple='false'
【发布时间】:2013-05-14 09:13:42
【问题描述】:

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

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

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

一切都很好。

但根据 entityA 的字段类型,有时我想将“多个”设置为 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,

        ));
}

这给了我以下错误:

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 

谁能帮帮我?

【问题讨论】:

  • 你确定这里出现了错误吗?
  • 是的,实际上是@DonCallisto
  • 我打赌没有。我敢打赌,您的实体中存在错误:您希望拥有一个 ArrayCollection,但您只有一个实体(对象),这会给您带来问题。
  • 但是当 multiple=true 时它正在工作? @DonCallisto 我检查了我的实体,但找不到任何异常
  • 为什么要让多个为假?

标签: php symfony


【解决方案1】:

在EntityA中,你有这样的东西,对吧?

public function setEntitiesB($data)
{
    $this->entitiesB = $data ;
}

现在因为您也可以接收单个值而不是值数组,所以您需要这样的东西:

public function setEntitiesB($data)
{
    if ( is_array($data) ) {
        $this->entitiesB = $data ;
    } else {
        $this->entitiesB->clear() ;
        $this->entitiesB->add($data) ;
    }
}

【讨论】:

    【解决方案2】:

    我会检查控制器中的 entityA 值,并根据它创建不同的表单。

    在控制器中:

    if ($entityA->getType() == 'a') { 
        $form = new FormB(); // form with multiple true
    } else {
        $form = new FormA(); // form with multiple false
    }
    

    【讨论】:

    • 我在尝试这个时仍然有同样的错误信息。 @Laurynas
    • 这不可能。 FormA 和 FormB 是两个独立的表单,应该区别对待,不会出现错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多