Lost Koder
Lost Koder

Reputation: 884

Apply validation before Data Transform

I want to transform a text field that I got from submitted user data to an Object in Symfony2. I used DataTransformer in order to do this. When I use built-in validators like 'NotEmpty' or 'NotNull' or any custom validators that built in standard way Symfony2 passes my specific object to them but I want to validate this text field before converting it to object. What should I do? (sry if my English is not so good)

Upvotes: 6

Views: 2516

Answers (1)

rolebi
rolebi

Reputation: 1181

Validation are always done on the reverse transformed data.

The best way to add validation rule before the transformation occurred is to use an event listener or subscriber on FormEvents::PRE_SUBMIT.

You'll get the raw data. Just apply your validation logic here then use the $event->getForm()->get('xxxx')->addError() method to add errors on the corresponding field.

More informations on event subscribers / listeners :

http://symfony.com/doc/current/components/form/form_events.html#event-listeners http://symfony.com/doc/current/components/form/form_events.html#event-subscribers

Upvotes: 6

Related Questions