将EventSubscriber添加到EventListener中

时间:2017-07-13 10:31:41

标签: symfony

我试图在EventListener中添加一个EventSubscriber on field add,有没有办法做到这一点?

快速举例:

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 个答案:

答案 0 :(得分:1)

您可以轻松地向表单本身添加EventSubscriber(而不是动态添加的phone字段)。然后在应用您的操作之前测试那里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');

    }