我正在尝试创建一个包含两个动态表单元素的动态表单。
我可以创建一个表单,显示新的表单元素的位置后,选择和提交体育。
然而,假设在选择位置并提交后,他们必须选择颜色,您将如何做到这一点?
我尝试为position添加一个新的事件侦听器,但它从未被调用过。
$builder->get('position')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier) {
// It's important here to fetch $event->getForm()->getData(), as
// $event->getData() will get you the client data (that is, the ID)
$position = $event->getForm()->getData();
dump($position);
$event->getForm()->add('colour', EntityType::class, [
'class' => Colour::class,
'placeholder' => '',
'choices' => ['red','green','blue'],
]);
}
);例如,在这个测试数据中,运动是足球,位置是前锋,允许的颜色是红色和绿色,对于位置守门员,颜色可能是黄色和黑色。
发布于 2021-09-16 10:07:22
您正在尝试将colour字段添加到错误的表单。
使用$event->getForm(),您检索的是“位置”表单,而不是您想要修改的主表单。
为了更好地解释这一点,我对您的代码进行了注释。
/* Here you're correctly registering an event listener to the "position" field, POST_SUBMIT event */
$builder->get('position')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier) {
// $event->getForm() here will return the "position" field form
$position = $event->getForm()->getData();
dump($position);
// In the documentation example here the $formModifier closure is used
// with $event->getForm()->getParent() as first argument
// What you missed here is the getParent() call
$event->getForm()
->getParent() // <- This will return the main form, the one you built with $builder
->add('colour', EntityType::class, [
'class' => Colour::class,
'placeholder' => '',
'choices' => ['red','green','blue'],
]);
}
);您在事件侦听器中遗漏的是在add调用之前的getParent()调用。
https://stackoverflow.com/questions/69194079
复制相似问题