问题
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();
}
回答1:
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;
}
回答2:
There is another possibility: Add an iterator to your form elements:
//controller
$idx = 1;
foreach ($list as $elem) {
$formBuilder->add('checkbox'.$idx,CheckboxType::class, ['label' => $elem->getName() ]);
$idx++;
}
Then it will iterate automatically in the twig:
//output.html.twig
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
When you define your own form theme you are able to address the form variables like:
{% form_theme form _self %}
{% block date_widget %}
{{ form.vars.value }}
{% endblock %}
来源:https://stackoverflow.com/questions/16440145/how-to-add-a-repeated-form-in-a-loop-symfony2-for-the-same-entity