I'm developing a Symfony2 application which uses a few forms. The data from the forms is persisted into a MySQL db using Doctrine2. I set up some constraints on the entities using Symfony annotations. Now, when the user fails to enter appropriate data into a form, he get's an error message, but, when I try to manipulate the same entities using a Command object I don't get any exception or error whatsoever.
From the documentation I read, Symfony's and Doctrine's validation work as separate mechanisms, now... is there a way to to make them work as one? What I'm trying to avoid is writing the same validations for the entity objects in order to use them as frontend and backend validations. Thanks.
The forms validate automatically when you call $form->isValid()
but if you want to validate an object outside of a form you have to call it manually.
In your command class just get the validator
service and validate your object before you persist it.
$validator = $this->container->get('validator');
$errors = $validator->validate($myEntity);
if (count($errors) > 0) {
return new Response(print_r($errors, true));
} else {
return new Response('The entity is valid!');
}
More in the documentation here http://symfony.com/doc/master/book/validation.html#using-the-validator-service
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With