我正在尝试将自定义事件订阅者关联到我的应用程序的所有表单。
我首先创建事件订阅者类
<?php
namespace AppBundle\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
/**
* Custom form listener.
*/
class FormListener implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array(
FormEvents::PRE_SUBMIT => 'onPreSubmit',
FormEvents::SUBMIT => 'onSubmit',
FormEvents::POST_SUBMIT => 'onPostSubmit',
FormEvents::PRE_SET_DATA => 'onPreSetData',
FormEvents::POST_SET_DATA => 'onPostSetData',
);
}
public function onPreSubmit(FormEvent $event)
{
// code here
}
public function onSubmit(FormEvent $event)
{
// code here
}
public function onPostSubmit(FormEvent $event)
{
// code here
}
public function onPreSetData(FormEvent $event)
{
// code here
}
public function onPostSetData(FormEvent $event)
{
// code here
}
}
我知道我可以将它关联到其 buildForm
函数内的表单
public function buildForm(FormBuilderInterface $builder, array $options)
{
// code here
->addEventSubscriber(new \AppBundle\EventListener\FormListener());
}
到目前为止一切正常。
现在的问题是:由于我想将此事件订阅者添加到我的应用程序的所有表单中(以执行一些常见检查并为表单操作提供 Hook ),我认为不要在每个表单中实例化我的事件订阅者,但是在服务容器内(在 services.yml 中)如下所示:
appbundle.form.listener:
class: AppBundle\EventListener\FormListener
tags:
- { name: kernel.event_subscriber }
不用说,第二种方法行不通。所以我的问题是:我做错了什么吗?是否可以监听表单外部表单事件?我的方法有问题吗?
最佳答案
您可以为 FormType 创建表单扩展,它是所有其他类型的基本类型。
表单扩展名应如下所示:
namespace AppBundle\Form\Extension;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormBuilderInterface;
class FormTypeExtension extends AbstractTypeExtension
{
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->addEventSubscriber(new \AppBundle\EventListener\FormListener());
}
public function getExtendedType()
{
return FormType::class;
}
}
然后在服务容器中注册此扩展,如下所示:
services:
app.form_type_extension:
class: AppBundle\Form\Extension\FormTypeExtension
tags:
- { name: form.type_extension, extended_type: Symfony\Component\Form\Extension\Core\Type\FromType }
更多引用the cookbook
关于php - Symfony2 : instantiating form event subscribers in service container,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37163731/