我正在使用事件侦听器来动态修改表单。我想向动态添加的字段添加另一个事件侦听器。我不知道如何实现这一点。
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
}
我尝试过使用$builder
in the buildForm
函数将事件监听器添加到second_field
但由于最初生成表单时该字段不存在,因此会引发错误。
如果我尝试通过执行以下操作在第一个事件侦听器中添加新的事件侦听器:
$form->get('second_field')->addEventListener(...)
然后我收到错误:
Call to undefined method Symfony\Component\Form\Form::addEventListener()
欢迎大家提出意见。