Symfony2: Change choices with ajax and validation

后端 未结 1 1587
野性不改
野性不改 2020-12-08 11:16

Scenario: I have a form with 2 selects. When user selects something from the first select, the second select gets populated with new values. This part works fine.

Bu

相关标签:
1条回答
  • 2020-12-08 11:40

    I think u have to use Events to manage this, which is more correct way

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('category', 'choice', array(
            'choices' => array(
                'foo' => 'foo',
                'bar' => 'bar'
            )
        ));
    
        $ff = $builder->getFormFactory();
    
        // function to add 'template' choice field dynamically 
        $func = function (FormEvent $e) use ($ff) {
            $data = $e->getData();
            $form = $e->getForm();
            if ($form->has('template')) {
                $form->remove('template');
            }
    
            $cat = isset($data['category'])?$data['category']:null;
    
            // here u can populate ur choices in a manner u do it in loadChoices
            $choices = array('1' => '1', '2' => '2');
            if ($cat == 'bar') {
                $choices = array('3' => '3', '4' => '4');
            }
    
            $form->add($ff->createNamed('template', 'choice', null, compact('choices')));
        };
    
        // Register the function above as EventListener on PreSet and PreBind
        $builder->addEventListener(FormEvents::PRE_SET_DATA, $func);
        $builder->addEventListener(FormEvents::PRE_BIND, $func);
    }
    
    0 讨论(0)
提交回复
热议问题