Bidirectional reference does not work Symfony2

89 views Asked by At

I'm using Sonata Admin Bundle to create the back-end, But I have a problem with One-to-Many : I have "Question" document which references one "QuizzPart":

/**
*@MongoDB\ReferenceOne(targetDocument="QuizzPart", inversedBy="questions") 
*/
protected $quizzPart ;

And the "QuizzPart" document references many questions :

/**
 * @var ArrayCollection
 * @MongoDB\ReferenceMany(targetDocument="Question",  mappedBy="quizzpart", cascade="all")
 */
protected $questions = array();

and this is how I add a QuizzPart to the Question With sonata admin :

$formMapper->add('quizzPart', 'sonata_type_model', array('by_reference' => true,
'required' => false)) ;

But when I add a Question and I set its QuizzPart there is no reference of the Question in the Quizzpart: This is the QuizzPart setter method :

public function setQuizzPart(\ATS\QuizzBundle\Document\QuizzPart $quizzPart)
  {

    $this->quizzPart = $quizzPart;
    $quizzPart->addQuestion($this);

    return $this;
  }

The question is not added to the QuizzPart object, Any one can help ?

1

There are 1 answers

6
stevenll On

You need to change the way quizz parts are added to your question entity. It should look like this:

public function addQuizzPart(QuizzPart $quizzPart)
{
    $this->quizzParts->add($quizzPart);
    $quizzPart->setQuestion($this); //This way the entities are "connected"        

    return $this;
}