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)
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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