请考虑以下订单表单:
META DATA:
Title: [________]
REQUIREMENTS:
What size? [_] Small [_] Medium [_] Large
What shape? [_] Circle [_] Square [_] Triangle
.
.
.
如何生成表单?
size
& shape
&应从另一个名为...
。Requirement
顺序
Class Order
{
private $title;
//OneToMany(targetEntity="Requirement", mappedBy="order")
private $requirements;
public function __construct()
{
$this->requirements = new ArrayCollection();
}
}
要求
Class Requirement
{
private $title;
//ManyToOne(targetEntity="Order", inversedBy="requirements")
private $order;
//OneToMany(targetEntity="Selection", mappedBy="selections")
private $selections;
public function __construct()
{
$this->selections = new ArrayCollection();
}
}
选择
Class Selection
{
private $title;
//ManyToOne(targetEntity="Requirement", inversedBy="selections")
private $requirement;
}
订单类型
class OrderType extends AbstractType
{
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'allow_extra_fields' => true
));
$resolver->setRequired('em');
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$em = $options['em'];
$requirements = $em->getRepository(Requirement::class)->findAll();
$form = $builder
->add('title', TextType::class, array());
foreach ($requirements as $requirement) {
$args['label'] = $requirement->getTitle();
$args['expanded'] = true;
$args['multiple'] = true;
$args['mapped'] = false;
$args['class'] = Selection::class;
$args['choice_label'] = 'title';
$args['choice_value'] = 'id';
$args['query_builder'] = call_user_func(function (EntityRepository $er, $requirement) {
return $er->createQueryBuilder('s')
->where('s.requirement = :requirement')
->setParameter('requirement', $requirement)
},$em->getRepository($args['class']), $requirement);
$form
->add($requirement->getTitle(), EntityType::class, $args);
}
$form
->add('submit', SubmitType::class, array(();
return $form;
}
}
这很好用,我可以坚持新的Order
。问题在于编辑Order
,如
$form->createView()
正确填写订单title
时,不会更新选择(复选框)。我甚至不知道这是否是在Symfony上这样做的正确方法。我不知道在渲染编辑实体表单时如何重新填充选中的复选框。
我不认为Symfony Form Collections是否是一个好主意,因为要求在时间上发生变化且无法硬编码为FormType
,因此应存储在数据库中。