5

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 ?

2
  • 1
    You can use the annotation @Assert\Valid on the property
    – Touki
    Commented Aug 23, 2013 at 12:52
  • That's it, thanks !! I thought @Assert\Type(...) would be enough..
    – Bonswouar
    Commented Aug 23, 2013 at 12:56

1 Answer 1

10

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
2
  • I would add the @Assert\Type(...\Person) to be sure it's a Person object. :)
    – Bonswouar
    Commented Aug 23, 2013 at 13:29
  • 4
    @Bonswouar Actually, you don't have to. Since property is locked, you should have a setBuyer(Person $person) method. PHP will trigger an error if the given type is wrong
    – Touki
    Commented Aug 23, 2013 at 13:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.