Symfony Form - Add required fields to form depending on other field value

喜你入骨 提交于 2021-01-29 10:53:14

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!