Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 : Recursive Validation

I've got an entity with some validators (not a form).

So I use $validator->validate($entity), but it doesn't validate my sub-ojects (the entity class has some others entity classes with some validators).

Is there an "automatic" way to do this, or I have to do $errorList->addAll($validator->validate($entity)); for each of them ?

like image 401
Bonswouar Avatar asked Aug 23 '13 12:08

Bonswouar


1 Answers

To allow recursive validation over objects you can simply use the Constraint @Assert\Valid

Example
Say a person has a mandatory last name

class Person
{
    /**
     * @Assert\NotNull
     * @var string
     */
    protected $lastName;
}

And you have a product, which have a buyer (Person)

class Product
{
    /**
     * @Assert\NotNull
     * @Assert\Valid
     * @var Person
     */
    protected $buyer;
}

By having NotNull and Valid, each time you validate the Product model it will check that:

  • It has a buyer
  • The buyer has a lastName
like image 68
Touki Avatar answered Nov 12 '22 02:11

Touki