2

我一直在寻找这个问题已经有一段时间了。好的,我在 symfony2 中动态加载表单到树枝。下面是代码:

class NewsType extends AbstractType
{   
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $formFactory = $builder->getFormFactory();

        $builder
            ->add('title')
            ->add('body')
            ->add('userType', 'choice', array(
            'choices' => array (
              'CT' => 'Contract',
              'PT' => 'Permanent',),))
            ->add('Save', 'submit')   
                 ->getForm()
        ;

        $builder->addEventListener(
        FormEvents::POST_BIND,
        function (FormEvent $event) use ($formFactory) {


            var_dump($event);

            $choices = array("key1" => "value1", "key2" => "value2");

            $event->getForm()->add(
              $formFactory->createNamed("my_dynamic_field_name", "choice", null, array(
                        "empty_value" => "Choose an option",
                        "auto_initialize" => false,
                        "label" => "My dynamic field: ",
                        "choices" => $choices
                    )
                )
            );


        }
        );
  }

    public function getName()
    {
        return 'remove_form_field';
    }

    // ...
}

what i want to achieve is that, when the 'userType' dropdown value is selected, an event should trigger and load 'my_dynamic_field_name' dropdown. 我怎么能做到这一点?(这没有使用提交按钮,当用户从下拉列表中选择一个值时,应该填充另一个下拉列表)

4

0 回答 0