我必须创建一名学校经理。当教师必须提交评估结果时,他必须通过评分等级评估给定的技能。
Evaluation
------ OneToMany ------ Scale
------ ManyToOne ------ Skill
EvaluationType
class EvaluationType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('scales', CollectionType::class, [
'entry_type' => ScaleType::class
]);
}
}
ScaleType
class ScaleType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('value');
}
}
我想动态地将ScaleType
子项添加到EvaluationType::scales
表单子项中,以获取Skill
的给定集合。
以下是我迄今为止在控制器操作中尝试过的内容:
public function newEvaluation(Classroom $classroom, Subject $subject, Period $period)
{
$evaluation = new Evaluation();
$evaluation->setClassroom($classroom);
$evaluation->setSubject($subject);
$evaluation->setPeriod($period);
$form = $this->createForm(EvaluationType::class, $evaluation);
$skills =$this->getDoctrine()->getRepository('AppBundle:Skill')->findAll();
foreach($skills as $skill) {
$scale = new Scale();
$scale->setEvaluation($evaluation);
$scale->setSkill($skill);
$form['scales']->add($this->createForm(ScaleType::class, $scale, [
'auto_initialize' => false
]));
}
return $this->render('classrooms/newEvaluation.html.twig', [
'form' => $form->createView(),
'classroom' => $classroom,
'subject' => $subject
]);
}
问题是我在渲染时只在scales
字段中获得了一个子表单,看起来当我将子项添加到$form['scales']
时,它会覆盖以前的子项。
我想我做错了。我怎样才能做到这一点?
我还指出我无法先创建Evaluation
,然后在另一页上创建所有Scale
。它需要在同一个控制器/页面中完成。
编辑:我将添加一个事实,即我不希望scales
的子项可扩展,它们必须由服务器修复,而不是被提取客户。
答案 0 :(得分:0)
解决了它,感谢Artamiel,这是我的新控制器动作:
public function newEvaluation(Classroom $classroom, Subject $subject, Period $period)
{
$evaluation = new Evaluation();
$evaluation->setClassroom($classroom);
$evaluation->setSubject($subject);
$evaluation->setPeriod($period);
$skills = $this->getDoctrine()->getRepository('AppBundle:Skill')->findAll();
foreach ($skills as $skill) {
$scale = new Scale();
$scale->setSkill($skill);
$scale->setEvaluation($evaluation);
}
$form = $this->createForm(EvaluationType::class, $evaluation);
return $this->render('classrooms/newEvaluation.html.twig', [
'form' => $form->createView(),
'classroom' => $classroom,
'subject' => $subject
]);
}