Cha*_*ase 2 php symfony-forms symfony symfony-2.3
我正在使用事件侦听器来动态修改表单.我想为动态添加的字段添加另一个事件监听器.我不知道如何实现这一目标.
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
}
Run Code Online (Sandbox Code Playgroud)
我只是使用函数$builder中的buildForm函数来添加事件监听器,second_field但因为在最初生成表单时该字段不存在会抛出错误.
如果我尝试通过执行以下操作在第一个事件侦听器中添加新事件侦听器:
$form->get('second_field')->addEventListener(...)
Run Code Online (Sandbox Code Playgroud)
然后我得到错误:
Call to undefined method Symfony\Component\Form\Form::addEventListener()
Run Code Online (Sandbox Code Playgroud)
欢迎大家提出意见.
Lev*_*min 12
如果,实际上是.
FormInterface没有addEventListener方法,但FormBuilderIntreface有它.如果要添加任何侦听器,则应按表单构建器创建表单字段.
例如:
// 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());
Run Code Online (Sandbox Code Playgroud)
您实际上不需要将事件侦听器添加到事件侦听器first_field或事件second_field侦听器本身。您可以将事件监听器保留在父表单上,并检查提交的数据和设置的数据是否包含 的数据first_field。如果是,请添加second_field. 在同一个监听器中,检查数据是否已设置或提交到second_field. 如果有,请添加第三个字段。
这里的文档中概述了类似的概念: http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html#cookbook-form-events-subscribed-data
| 归档时间: |
|
| 查看次数: |
7230 次 |
| 最近记录: |