如何添加重复的形式在一个循环的Symfony2同一实体(How to add a repeated

2019-09-02 05:34发布

我想建立一个调查表。 当我使用下面的代码,我只能看到我的表的最后一个问题,它包含18个问题(和答案场)。

因为我的问卷调查将是比较复杂,我不能使用集合,有些问题与多个答案,有些则在真/假,等我简化了代码先解决这个问题。

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

Answer 1:

问题解决了,感谢朋友。 我不得不更换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; 
  } 


Answer 2:

还有另一种可能性:一个迭代器添加到您的表单元素:

//controller
$idx = 1;
foreach ($list as $elem) {
  $formBuilder->add('checkbox'.$idx,CheckboxType::class, ['label' => $elem->getName() ]);
  $idx++;
}

然后,它会在树枝自动遍历:

//output.html.twig
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}

当你定义自己的表单主题,你能解决诸如表单变量:

{% form_theme form _self %}
{% block date_widget %}
  {{ form.vars.value }} 
{% endblock %}


文章来源: How to add a repeated form in a loop symfony2 for the same entity