如何在循环symfony2中为同一实体添加重复的表单

问题描述 投票:0回答:2

我想建立一份问卷表。当我使用下面的代码时,我只能看到我的表的最后一个问题,其中包含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();
}
php forms loops symfony formbuilder
2个回答
3
投票

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

0
投票

还有另一种可能性:向表单元素添加迭代器:

//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 %}
© www.soinside.com 2019 - 2024. All rights reserved.