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.

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

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 :

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?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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

Solution 2

i would check the entityA value in the controller and depending on it create different forms.

in controller:

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

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply