如何在循环symfony2中为同一实体添加重复形式 [英] How to add a repeated form in a loop symfony2 for the same entity

查看:87
本文介绍了如何在循环symfony2中为同一实体添加重复形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想建立一个调查表. 当我使用以下代码时,我只能看到表格中的最后一个问题,该问题包含18个问题(以及答案字段).

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

推荐答案

问题已解决,多亏了一位朋友. 我不得不替换createformBuilder

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

这篇关于如何在循环symfony2中为同一实体添加重复形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆