I have a Quiz structure with three entities:
- Quiz has questions (OneToMany)
- Question has Quiz (ManyToOne)
- Question has answers (OneToMany)
- The answer has a question (ManyToOne)
The code looks like this:
Quiz entity
class Quiz { /** * @ORM\OneToMany(targetEntity="Question", mappedBy="quiz", cascade={"persist", "remove"}) */ private $questions; public function __construct() { $this->questions = new ArrayCollection(); } public function addQuestion(\Cariboo\QuizBundle\Entity\Question $questions) { $questions->setQuiz( $this ); // die(); Not dying here... $this->questions[] = $questions; return $this; } public function removeQuestion(\Cariboo\QuizBundle\Entity\Question $questions) { $this->questions->removeElement($questions); } public function getQuestions() { return $this->questions; } }
Question Object
class Question { private $answers; private $quiz; public function addAnswer(\Cariboo\QuizBundle\Entity\Answer $answers) { $answers->setQuestion( $this ); $this->answers[] = $answers; return $this; } public function removeAnswer(\Cariboo\QuizBundle\Entity\Answer $answers) { $this->answers->removeElement($answers); } public function getAnswers() { return $this->answers; } public function setQuiz(\Cariboo\QuizBundle\Entity\Quiz $quiz = null) { $this->quiz = $quiz; return $this; } public function getQuiz() { return $this->quiz; } }
Response object
class Answer { private $question; public function setQuestion(\Cariboo\QuizBundle\Entity\Question $question = null) { $this->question = $question; return $this; } public function getQuestion() { return $this->question; } }
I cascade save them.
I configured my setters as described in Cascaded persist not working (Doctrine ORM + Symfony 2)
The addAnswer request is executed and the responses to it are set correctly. However addQuestion does not set the quiz.
image of what is reset when the form is submitted
I can add foreach to my controller, but I am not satisfied with this, since I feel that I am not using the power of symfony. (No duplicate object matches correctly )
if ( $form->isValid() ) { foreach ( $quiz->getQuestions() as $question ) { $question->setQuiz( $quiz ); } $em = $this->getDoctrine()->getManager(); $em->persist( $quiz ); $em->flush(); return $this->redirect( $this->generateUrl( 'quiz_show', array( 'slug' => $quiz->getSlug() ) ) ); }
I cannot understand why addQuestion not running.
Edit
My Quiz Form
$builder ->add( 'questions', 'collection', array( 'type' => new QuestionType(), 'allow_add' => true, 'allow_delete' => true, 'prototype' => true, 'prototype_name' => '__qst_prot__' ) ) ;
Partial Builder Question
$builder ->add( 'question', 'text' ) ->add( 'answers', 'collection', array( 'type' => new AnswerType(), 'allow_add' => true, 'allow_delete' => true, 'prototype' => true, 'prototype_name' => '__asw_prot__' ) );
My Answer form
$builder ->add( 'answer', 'text' ) ->add( 'correct' ) ;