【发布时间】:2021-06-23 09:31:30
【问题描述】:
我想要 3 个选择字段,其中可用选项取决于前一个字段的选定值。
按照文档中的示例,我设法使这项工作适用于两个选择字段: https://symfony.com/doc/current/form/dynamic_form_modification.html#dynamic-generation-for-submitted-forms
但我无法解决添加第三个选择字段的问题。 例如:公司 -> 部门 -> 地点
company 字段通过$builder->get('company')->addEventListener() 有一个FormEvents::POST_SUBMIT 事件侦听器,因为您不能将子表单添加到提交的表单,事件侦听器被添加到仍然可以将子表单添加到父表单的子表单。没有这个,提交时数据为空。
这是一个问题,因为无法将相同的事件侦听器添加到部门字段,因为通过 $builder->get('department')->addEventListener() 添加时,该字段不存在,因为它已添加到事件侦听器中。
// src/Form/Type/CompanyType.php
namespace App\Form\Type;
use App\Entity\Department;
use App\Entity\Company;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormInterface;
// ...
class CompanyMeetupType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('company', EntityType::class, [
'class' => Company::class,
'placeholder' => '',
])
;
$formModifier = function (FormInterface $form, Company $company = null) {
$departments = null === $company ? [] : $company->getAvailableDepartments();
$form->add('department', EntityType::class, [
'class' => Department::class,
'placeholder' => '',
'choices' => $$departments,
]);
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier) {
$data = $event->getData();
$formModifier($event->getForm(), $data->getCompany());
}
);
$builder->get('company')->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)
$company = $event->getForm()->getData();
// since we've added the listener to the child, we'll have to pass on
// the parent to the callback functions!
$formModifier($event->getForm()->getParent(), $company);
}
);
}
// ...
}
【问题讨论】: