Symfony2 - Dynamic form choices - validation remove

前端 未结 5 1079
挽巷
挽巷 2021-01-02 00:28

I have a drop down form element. Initially it starts out empty but it is populated with values via javascript after the user has made some interactions. Thats all working

5条回答
  •  醉话见心
    2021-01-02 00:49

    Found a better solution which I posted here: Disable backend validation for choice field in Symfony 2 Type

    Old answer:

    Just spent a few hours dealing with that problem. This choice - type is really annoying. My solution is similar to yours, maybe a little shorter. Of course it's a hack but what can you do...

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('place', 'choice'); //don't validate that
    
        //... more form fields
    
       //before submit remove the field and set the submitted choice as
       //"static" choices to make "ChoiceToValueTransformer" happy
       $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
            $data = $event->getData();
            $form = $event->getForm();
            if ($form->has('place')) {
                $form->remove('place');
            }
    
            $form->add('place', 'choice', array(
                'choices' => array($data['place']=>'Whatever'),
            ));
        });
    }
    

提交回复
热议问题