我目前正在学习Symfony 2框架,并在嵌套集合表单类型上进行了一些努力。
我正在尝试构建一个简单的嵌套集合表单,其中的实体建模如下:
MySurvey has many MyQuestions
MyQuestions has many MyAnswer
Each MyAnswer holds a possible value for the linked MyQuestion
我的目标是提供一个表单,显示调查中的所有问题以及显示所有可用答案的每个问题作为单选按钮(选项)。 我能够将答案显示为文本字段,但不能作为选择......
这是我的代码:
以下是实体:
class MySurvey
{
....
/**
* @ORM\ManyToMany(targetEntity="MyQuestion")
* @ORM\JoinTable(name="my_survey_questions",
* joinColumns={@ORM\JoinColumn(name="survey_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="question_id", referencedColumnName="id")}
* )
*/
protected $questions;
...
}
class MyQuestion
{
...
/**
* @ORM\Column(type="string", length=255)
*/
protected $title;
/**
* @ORM\ManyToMany(targetEntity="MyAnswer")
* @ORM\JoinTable(name="question_answers",
* joinColumns={@ORM\JoinColumn(name="question_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="answer_id", referencedColumnName="id")}
* )
*/
protected $answers;
...
}
class MyAnswer
{
....
/**
* @ORM\Column(type="string", length=255)
*/
protected $value;
...
}
以下是我的表单类型:
class MySurveyFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('questions', 'collection', array('type' => new MyQuestionFormType()));
}
...
}
class MyQuestionFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('answers', 'collection', array('type' => new MyAnswerFormType()));
}
...
}
class MyAnswerFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('value');
}
...
}
这是我的模板:
{% extends 'base.html.twig' %}
{% block body %}
<form method="post" {{ form_enctype(form) }}>
{{ form_errors(form) }}
{% set i = 0 %}
<ol>
{% for question in form.questions %}
<br />
<li>
{{ questions[i].title }}<br /><br />
{% set j = 0 %}
{% for answer in question.answers %}
{{ form_widget(question.answers[j]) }}
{% set j = j + 1 %}
{% endfor %}
{% set i = i + 1 %}
</li>
{% endfor %}
</ol>
<input type="submit" class="btn btn-primary" />
</form>
{% endblock %}
我尝试在MyQuestionFormType中更改我的buildForm函数,以便选择问题的正确答案。但是为了使这个解决方案有效,我需要获得每个问题的答案,而且我不知道如何完成这个。
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('answers', 'entity', array(
'class' => 'AppBundle:MyAnswer',
'choices' => ???
));
}
如果我将调查作为参数传递给控制器,是否有办法获得当前问题&#34; myQuestionFormType中的值,以便我可以检索它的答案?
$form = $this->createForm(new MySurveyFormType($survey->getQuestions()), $survey);
任何帮助表示赞赏!
非常感谢