Validating dynamically loaded choices in Symfony 2

后端 未结 5 1347
独厮守ぢ
独厮守ぢ 2020-12-08 16:08

I have a choice field type named *sub_choice* in my form whose choices will be dynamically loaded through AJAX depending on the selected value of the parent choice field, na

5条回答
  •  佛祖请我去吃肉
    2020-12-08 16:21

    To do the trick you need to overwrite the sub_choice field before submitting the form:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        ...
    
        $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
            $parentChoice = $event->getData();
            $subChoices = $this->getValidChoicesFor($parentChoice);
    
            $event->getForm()->add('sub_choice', 'choice', [
                'label'   => 'Sub Choice',
                'choices' => $subChoices,
            ]);
        });
    }
    

提交回复
热议问题