Search code examples
phpformsloopssymfonyformbuilder

How to add a repeated form in a loop symfony2 for the same entity


I want to build a questionnaire form. When I use the following code, I can only see the last question of my table that contains 18 questions (and the answer field).

I can't use a collection because my questionnaire is going to be more complicated, some questions with multiple answers, some others in true/false, etc. I simplified the code to fix this problem first.

    //Get question array collection
    $questions = $questionnaire->getQuestions();
    $formBuilderQuestionnaire = $this->createFormBuilder();

    //Make a loop for each question
    foreach($questions as $question)
    {
        //Create an answer form
        $answer = new Answers($question, $evaluation);
        $formBuilder = $this->createFormBuilder($answer);

        //Add a answer text box with the question as label
        $formBuilder->add('answerText', 'textarea',  array(
        'required' => false,
        'label' => $question->getQuestionText()
        ));

        $formBuilderQuestionnaire->add($formBuilder);

    }

    //Create the form
    $form = $formBuilderQuestionnaire->getForm();
    return $form->createView();
}

Solution

  • Problem solved, thanks to a friend. I had to replace the createformBuilder

       public function generateForm($questionnaire, $evaluation)
    {
    
        //Get question array collection
        $questions = $questionnaire->getQuestions();
        $formBuilderQuestionnaire = $this->createFormBuilder();
        $i = 0;
    
    
        //Make a loop for each question
        foreach($questions as $question)
        {
    
            //Create an answer form
            $answer = new Answers($question, $evaluation);
            $formBuilder = $this->get('form.factory')->createNamedBuilder($i, 'form', $answer);
    
    
            //Add a answer text box with the question as label
            $formBuilder->add('answerText' , 'textarea',  array(
                'required' => false,
                'label' => $question->getQuestionText() 
            ));
    
            $formBuilderQuestionnaire->add($formBuilder);
    
            $i++;
    
        }
    
        //Create the form
        $form = $formBuilderQuestionnaire->getForm();
        return $form; 
      }