2017-07-13 2 views
1

Ich versuche, während eines EventListener einen EventSubscriber im Feld add hinzuzufügen, gibt es eine Möglichkeit, dies zu tun?Hinzufügen eines EventSubscriber zu einem EventListener

Schnell Beispiel:

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()); 
} 

Antwort

1

Sie können ganz einfach ein EventSubscriber auf die Form selbst (nicht auf die dynamisch hinzugefügt phone Feld) hinzuzufügen. Testen Sie dann das Feld phone, bevor Sie Ihre Aktionen anwenden.

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

Danke für die Tipps! :) – Charly

Verwandte Themen