2017-07-13 13 views
1

EventListener中にフィールドの追加にEventSubscriberを追加しようとしていますが、これを行う方法はありますか?EventListenerにEventSubscriberを追加する

クイック例:あなたは簡単に(ない動的に追加phoneフィールドに)フォーム自体にEventSubscriberを追加することができます

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) { 
     $form = $event->getForm(); 
     ->add('phone', TextType::class, array(
      ... 
     )); 

    // There I want to add the EventSubscriber on the field Phone 
    // I would have done this if I had access to the FormBuilder 
    $builder->get('phone')->addEventSubscriber(new StripWhitespaceListener()); 
} 

答えて

1

。次に、あなたの行動を適用する前に、phoneフィールドの存在をテストします。

use Symfony\Component\Form\AbstractType; 
use Symfony\Component\EventDispatcher\EventSubscriberInterface; 
use Symfony\Component\Form\FormEvent; 
use Symfony\Component\Form\FormEvents; 

class YourFormType extends AbstractType implements EventSubscriberInterface 
{ 

    /** {@inheritdoc} */ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     // ... 
     $builder->addEventSubscriber($this); 
    } 

    /** {@inheritdoc} */ 
    public static function getSubscribedEvents() 
    { 
     return [ 
      FormEvents::POST_SUBMIT => [['onPreValidate', 900]], 
     ]; 
    } 

    /** @param FormEvent $event */ 
    public function onPreValidate(FormEvent $event) 
    { 
     $form = $event->getForm(); 
     // test for field existance 
     if (!$form->has('phone')) { 

      return; 
     } 
     // field exists! apply stuff to the field ... 
     $phoneField = $form->get('phone'); 

    } 
+0

ヒントをお願いします! :) – Charly

関連する問題