Charly
Charly

Reputation: 446

add an EventSubscriber into an EventListener

I'm trying to add an EventSubscriber on field add during an EventListener, is there a way to do this ?

Quick example:

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

Upvotes: 1

Views: 94

Answers (1)

Nicolai Fröhlich
Nicolai Fröhlich

Reputation: 52483

You can easily add an EventSubscriber to the form itself (not to the dynamically added phone field). Then test for the existance of the phone field there before applying your actions.

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');

    }

Upvotes: 1

Related Questions