问题
I want to add some required fields to my form when an other field has some value. I've tried to do it with PRE_SET_DATA event but I cannot get data in my event.
My example here is to add partner name field when a user is married.
My UserType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('familyStatus', ChoiceType::class, [
'label' => 'Statut de famille',
'label_attr' => [
'class' => 'fg-label'
],
'attr' => [
'class' => 'sc-gqjmRU fQXahQ'
],
'required' => true,
'choices' => [
'Married' => 'M',
'Single' => 'S'
]
])
->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$form = $event->getForm();
$user = $event->getData();
$status = $user->getFamilyStatus(); // Give me NULL
//$status = $form->get('familyStatus')->getData() Give me NULL too
/*
if ($user && $status === 'M') {
$form->add('partnerName', TextType::class, [
'required' => true,
'mapped' => false
]);
)
*/
})
;
}
What's wrong ? How can I add dynamically new fields depending on other field ? I also tried with POST_SET_DATA but it's not working.
回答1:
You need the second example from this part of the docs link.
Basically you set the event listener to the entire form. You should add another listener to the field itself with POST_SUBMIT event.
来源:https://stackoverflow.com/questions/62138143/symfony-form-add-required-fields-to-form-depending-on-other-field-value