如何使用 Symfony Forms 将事件侦听器添加到动态添加的字段 [英] How to add an Event Listener to a dynamically added field using Symfony Forms

查看:24
本文介绍了如何使用 Symfony Forms 将事件侦听器添加到动态添加的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用事件侦听器来动态修改表单.我想向动态添加的字段添加另一个事件侦听器.我不知道如何做到这一点.

I am using event listeners to dynamically modify a form. I want to add another event listener to a field that was added dynamically. Im not sure how to accomplish this.

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('first_field','choice',array(
        'choices'=>array('1'=>'First Choice','2'=>'Second Choice')
    ));

    $builder->addEventListener(FormEvents::PRE_SET_DATA, array($this, 'preSetData'));
    $builder->get('first_field')->addEventListener(FormEvents::POST_SUBMIT, array($this, 'postSubmit'));
}

public function preSetData(FormEvent $event)
{
    $form = $event->getForm();
    $form->add('second_field','choice',array(
        'choices'=>array('1'=>'First Choice','2'=>'Second Choice')
    ));
    //Some how add an event listener to this field

}

public function postSubmit(FormEvent $event)
{
    $form = $event->getForm()->getParent();
    $form->add('second_field','choice',array(
        'choices'=>array('1'=>'First Choice','2'=>'Second Choice')
    ));
    //Some how add an event listener to this field
}

我尝试使用 buildForm 函数中的 $builder 将事件侦听器添加到 second_field 但因为该字段不存在当表单最初生成时,它会抛出一个错误.

I have trie just using the $builder in the buildForm function to add the event listener to the second_field but because the field doesnt exist when the form is initially generated it throws an error.

如果我尝试通过执行以下操作在第一个事件侦听器中添加新的事件侦听器:

If i try and add the new event listener inside the first event listener by doing:

$form->get('second_field')->addEventListener(...)

然后我得到错误:

Call to undefined method Symfony\Component\Form\Form::addEventListener() 

欢迎提出任何建议.

推荐答案

如果,是真的吗.

FormInterface 没有 addEventListener 方法,但是 FormBuilderIntreface 有.如果你想添加任何监听器,你应该通过表单构建器创建表单字段.

FormInterface does't have the addEventListener method, but FormBuilderIntreface have it. If you want to add any listener, you should to create form field by form builder.

例如:

   // create builder for field
   $builder = $form->getConfig()->getFormFactory()->createNamedBuilder($name, $type, null, array(
       /** any options **/
       'auto_initialize'=>false // it's important!!!
   ));
   // now you can add listener
   $builder->addEventListener(FormEvents::POST_SUBMIT, $yourCallbackHere)

   // and only now you can add field to form  
   $form->add($builder->getForm());

这篇关于如何使用 Symfony Forms 将事件侦听器添加到动态添加的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆