我想建立一份问卷表。当我使用下面的代码时,我只能看到我的表的最后一个问题,其中包含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();
}
问题解决了,感谢朋友。我不得不替换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;
}
还有另一种可能性:向表单元素添加迭代器:
//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 %}