Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use symfony2 entity validations as doctrine validations?

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.

like image 575
Muc Avatar asked Dec 21 '22 19:12

Muc


1 Answers

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

like image 100
MDrollette Avatar answered Dec 26 '22 15:12

MDrollette