2016-05-11 3 views
1

私のアプリケーションのすべてのフォームにカスタムイベントサブスクライバを関連付けようとしています。 Symfony2:サービスコンテナのフォームイベントサブスクライバのインスタンス化

は、私はその buildForm機能

public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     // code here 

     ->addEventSubscriber(new \AppBundle\EventListener\FormListener()); 
    } 

内のフォームにそれを関連付けることができます知っているイベント加入者クラス

<?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 
     } 

    } 

を作成することによって開始し、すべてのものは、これまで正常に動作します。

これは私のアプリケーションのすべてのフォームにこのイベントデジグネータを追加したいので(共通のチェックを行い、フォーム操作のフックを提供するため)、私はイベントのサブスクライバを各フォーム内でインスタンス化しないと思っていました。しかし、このような(services.yml中)サービスコンテナ内:回答

appbundle.form.listener: 
     class: AppBundle\EventListener\FormListener 
     tags: 
      - { name: kernel.event_subscriber } 

言うまでもなく、この第2のアプローチは機能していません。だから私の質問です:私は何か間違っている?フォームイベントに耳を傾けることが可能ですフォーム?私のアプローチに何か問題がありますか?

答えて

2

他のすべての基本タイプである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; 
    } 
} 

次に、このようなサービスコンテナにこの拡張機能を登録します。the cookbook

services: 
    app.form_type_extension: 
     class: AppBundle\Form\Extension\FormTypeExtension 
     tags: 
      - { name: form.type_extension, extended_type: Symfony\Component\Form\Extension\Core\Type\FromType } 

をさらに参照

関連する問題