Object of class Doctrine\ORM\PersistentCollection could not be converted to string

Gianni Alessandro picture Gianni Alessandro · Jan 26, 2014 · Viewed 17.6k times · Source

I made a web application with Symfony2, in which a User has an array correlation ManytoMany with the entity Mission. The User can upload the entity $product through a form, and one of the data passed by the form is the mission associated to the user.

When I try to upload the data, appears the error:

ContextErrorException: Catchable Fatal Error: Object of class   
Doctrine\ORM\PersistentCollection could not be converted to string in     
C:\BitNami\wampstack-5.4.23- 
0\frameworks\symfony\vendor\doctrine\dbal\lib\Doctrine\DBAL\Statement.php line 103

It's clear that Doctrine don't know how to save the value of the mission.

How can I manage it?

I didn't know neither how to declare the mission object in my product entity. Now is simply like this:

/**
 * @var string
 *
 * @ORM\Column(name="mission", type="string", length=255)
 */
protected $mission;

UPDATE ---

My controller now is:

       $form = $this->createFormBuilder($product)
           ->add('name', 'text')
           ->add('mission', 'entity', array('required' => true, 'multiple' => false, 'class' => 'AcmeManagementBundle:Mission', 'query_builder' => function($repository) { return $repository->createQueryBuilder('c')->orderBy('c.id', 'ASC'); },))              
      //...
           ->add('save', 'submit')
           ->getForm(); 

UPDATE ---

Now works, but I have a problem. When appears the form to upload the $product object, appears also the ->add('mission', 'entity'... In this field I can see all the mission stored, and not only the ones associated with the user. How should I change my controller? I tried to change my controller like this:

       $product = new Product();
       $product->setMission($this->getUser()->getMission());

Answer

Vincent Barrault picture Vincent Barrault · Jan 27, 2014

For manage a ManyToMany relation between User and Mission

in User.php:

/**
 * @var \Doctrine\Common\Collections\ArrayCollection
 * 
 * @ORM\ManyToMany(targetEntity="Your\SuperBundle\Entity\Mission", inversedBy="users", orphanRemoval=true)
 * @ORM\JoinTable(name="user_mission")
 */
private $missions;

in Mission.php:

/**
 * @var \Doctrine\Common\Collections\ArrayCollection
 *
 * @ORM\ManyToMany(targetEntity="Your\SuperBundle\Entity\User", mappedBy="missions", cascade={"all"}, orphanRemoval=true)
 */
private $users;

then for your form:

http://symfony.com/doc/current/reference/forms/types/collection.html for manage collection of Mission in your User form.

take a look at "type" and "allow_add"