0

我想建立一个调查表。当我使用以下代码时,我只能看到包含 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();
}
4

2 回答 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; 
  } 
于 2013-05-14T08:47:38.040 回答
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 %}
于 2019-04-14T15:23:13.147 回答