Symfony2: automatic validation

Saturday, April 12, 2014 18:45
riska Tags: , Back

If you used validators previously, then you would probably know that sometimes you have to validate the objects manually. This may happen if a controller receives an Ajax request (which doesn’t contain any forms) or an action manipulates several objects.

First, let’s take a look at the old way of validating objects:

Yes, you have to get the validator from the service manager every time you want to validate an object. Furthermode, you have to call the validate method on all changed/created objects to do the validation.

So, let’s see a better solution for this problem. Our first step is to create a new exception class which will be thrown if one of the objects is invalid:

This will do it for now. The next class we have to create is the validator class itself. This class will be an event handler which will validate the added and changed classes. Take a look at the code:

Okay, what can we see above? The constructor gets the validation service from DI. Using the preFlush event hook we subscribe the flush event, but our code will run before the flush event. This mechanism ensures that if something goes wrong, an exception will be thrown and the flush command won’t be finished. By handling the exception you can fix the validation:

Note that after this modification the flush() method may throw exception which should be handled or your application crashes.

We haven’t finished yet! The last step is to register our new service in services.yml / services.xml:

Note: if you use MongoDB, you will have to use the doctrine_mongodb.odm.event_listener listener and the PreFlushEventArgs will come from other namespace.

No comments fo far.

Leave a Reply