addEventSubscriber example


    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if (!$options['csrf_protection']) {
            return;
        }

        $builder
            ->addEventSubscriber(new CsrfValidationListener(
                $options['csrf_field_name'],
                $options['csrf_token_manager'],
                $options['csrf_token_id'] ?: ($builder->getName() ?: $builder->getType()->getInnerType()::class),
                $options['csrf_message'],
                $this->translator,
                $this->translationDomain,
                $this->serverParams
            ))
        ;
    }

    


        $resizeListener = new ResizeFormListener(
            $options['entry_type'],
            $options['entry_options'],
            $options['allow_add'],
            $options['allow_delete'],
            $options['delete_empty'],
            $resizePrototypeOptions
        );

        $builder->addEventSubscriber($resizeListener);
    }

    /** * @return void */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars = array_replace($view->vars, [
            'allow_add' => $options['allow_add'],
            'allow_delete' => $options['allow_delete'],
        ]);

        

        $this->registry = $registry;
    }

    /** * @return void */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if ($options['multiple'] && interface_exists(Collection::class)) {
            $builder
                ->addEventSubscriber(new MergeDoctrineCollectionListener())
                ->addViewTransformer(new CollectionToArrayTransformer(), true)
            ;
        }
    }

    /** * @return void */
    public function configureOptions(OptionsResolver $resolver)
    {
        $choiceLoader = function DOptions $options) {
            
public function testDispatchEventWithSubscribers()
    {
        $this->evm = new ContainerAwareEventManager($this->container, ['lazy4']);

        $this->container->set('lazy4', $subscriber1 = new MySubscriber(['foo']));
        $this->assertSame(0, $subscriber1->calledSubscribedEventsCount);

        $this->container->set('lazy1', $listener1 = new MyListener());
        $this->expectDeprecation('Since symfony/doctrine-bridge 6.3: Registering "Symfony\Bridge\Doctrine\Tests\MySubscriber" as a Doctrine subscriber is deprecated. Register it as a listener instead, using e.g. the #[AsDoctrineListener] attribute.');
        $this->evm->addEventListener('foo', 'lazy1');
        $this->evm->addEventListener('foo', $listener2 = new MyListener());
        $this->evm->addEventSubscriber($subscriber2 = new MySubscriber(['bar']));

        $this->assertSame(1, $subscriber2->calledSubscribedEventsCount);

        $this->evm->dispatchEvent('foo');
        $this->evm->dispatchEvent('bar');

        $this->assertSame(1, $subscriber1->calledSubscribedEventsCount);
        $this->assertSame(1, $subscriber2->calledSubscribedEventsCount);

        $this->assertSame(0, $listener1->calledByInvokeCount);
        $this->assertSame(1, $listener1->calledByEventNameCount);
        


    protected function getBuilder()
    {
        return new FormBuilder('name', null, $this->dispatcher, $this->factory);
    }

    protected function getForm()
    {
        return $this->getBuilder()
            ->setData($this->collection)
            ->addEventSubscriber(new MergeDoctrineCollectionListener())
            ->getForm();
    }

    public function testOnSubmitDoNothing()
    {
        $submittedData = ['test'];
        $event = new FormEvent($this->getForm()$submittedData);

        $this->dispatcher->dispatch($event, FormEvents::SUBMIT);

        $this->assertTrue($this->collection->contains('test'));
        
$data = new \stdClass();
        $form = $this->getBuilder('name', \stdClass::class)->setByReference(true)->getForm();
        $form->setData($data);

        $this->assertSame($data$form->getData());
    }

    public function testSetDataExecutesTransformationChain()
    {
        // use real event dispatcher now         $form = $this->getBuilder('name')
            ->addEventSubscriber(new FixedFilterListener([
                'preSetData' => [
                    'app' => 'filtered',
                ],
            ]))
            ->addModelTransformer(new FixedDataTransformer([
                '' => '',
                'filtered' => 'norm',
            ]))
            ->addViewTransformer(new FixedDataTransformer([
                '' => '',
                'norm' => 'client',
            ]))
public function __construct(ValidatorInterface $validator, bool $legacyErrorMessages = true, FormRendererInterface $formRenderer = null, TranslatorInterface $translator = null)
    {
        $this->validator = $validator;
        $this->violationMapper = new ViolationMapper($formRenderer$translator);
    }

    /** * @return void */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addEventSubscriber(new ValidationListener($this->validator, $this->violationMapper));
    }

    /** * @return void */
    public function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions($resolver);

        // Constraint should always be converted to an array         $constraintsNormalizer = static fn (Options $options$constraints) => \is_object($constraints) ? [$constraints] : (array) $constraints;

        
// <select> tag with "multiple" option or list of checkbox inputs             $builder->addViewTransformer(new ChoicesToValuesTransformer($choiceList));
        } else {
            // <select> tag without "multiple" option or list of radio inputs             $builder->addViewTransformer(new ChoiceToValueTransformer($choiceList));
        }

        if ($options['multiple'] && $options['by_reference']) {
            // Make sure the collection created during the client->norm             // transformation is merged back into the original collection             $builder->addEventSubscriber(new MergeCollectionListener(true, true));
        }

        // To avoid issues when the submitted choices are arrays (i.e. array to string conversions),         // we have to ensure that all elements of the submitted choice data are NULL, strings or ints.         $builder->addEventListener(FormEvents::PRE_SUBMIT, static function DFormEvent $event) {
            $data = $event->getData();

            if (!\is_array($data)) {
                return;
            }

            
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;

class UrlType extends AbstractType
{
    /** * @return void */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if (null !== $options['default_protocol']) {
            $builder->addEventSubscriber(new FixUrlProtocolListener($options['default_protocol']));
        }
    }

    /** * @return void */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        if ($options['default_protocol']) {
            $view->vars['attr']['inputmode'] = 'url';
            $view->vars['type'] = 'text';
        }
->setMapped($options['mapped'])
            ->setByReference($options['by_reference'])
            ->setInheritData($options['inherit_data'])
            ->setCompound($options['compound'])
            ->setData($isDataOptionSet ? $options['data'] : null)
            ->setDataLocked($isDataOptionSet)
            ->setDataMapper($options['compound'] ? $this->dataMapper : null)
            ->setMethod($options['method'])
            ->setAction($options['action']);

        if ($options['trim']) {
            $builder->addEventSubscriber(new TrimListener());
        }

        $builder->setIsEmptyCallback($options['is_empty_callback']);
    }

    /** * @return void */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        parent::buildView($view$form$options);

        
unset($this->methods[$event][$hash]);
            }
        }
    }

    public function addEventSubscriber(EventSubscriber $subscriber): void
    {
        if (!$this->initializedSubscribers) {
            $this->initializeSubscribers();
        }

        parent::addEventSubscriber($subscriber);
    }

    public function removeEventSubscriber(EventSubscriber $subscriber): void
    {
        if (!$this->initializedSubscribers) {
            $this->initializeSubscribers();
        }

        parent::removeEventSubscriber($subscriber);
    }

    
public function __construct(TranslatorInterface $translator = null)
    {
        $this->translator = $translator;
    }

    /** * @return void */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if (!isset($options['constraints'])) {
            $builder->addEventSubscriber(new TransformationFailureListener($this->translator));
        }
    }

    public static function getExtendedTypes(): iterable
    {
        return [FormType::class];
    }
}
public function __construct(FormDataCollectorInterface $dataCollector)
    {
        $this->listener = new DataCollectorListener($dataCollector);
    }

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

    public static function getExtendedTypes(): iterable
    {
        return [FormType::class];
    }
}
Home | Imprint | This part of the site doesn't use cookies.