3

I'm using the Symfony Validator on it's own, without the forms component.

I have an entity which contains a child entity, currently I can validate that that field is an instance of the child entity, but I need it to also validate the child for it's constraints.

#validation.yml
# This is the entity I'm validating against, it checks the type but doesn't then validate 
# it against the child entity below. 
Greg\PropertyBundle\Entity\Property:
    properties:
        property_id:
            - NotBlank: ~
            - Type:
                type: string
        addresses:
            - All:
                - Type:
                    type: Greg\PropertyBundle\Entity\Address

# child entity
Greg\PropertyBundle\Entity\Address:
    properties:
        city:
            - NotBlank: ~
            - Type:
                type: string

To call the validator I'm passing it in with DI to one of my services and doing this:

// Validate the data
$errorList = $this->validator->validate($data);

I have also tried it by passing in the following flags:

$errorList = $this->validator->validate($data, null, true, true);
greg
  • 6,853
  • 15
  • 58
  • 71

1 Answers1

6

By default validation is not delegated for objects in properties. If you want to invoke validation process for children objects then you should use specific constraint "Valid".

So your validation script will be:

#validation.yml
# This is the entity I'm validating against, it checks the type but doesn't then validate 
# it against the child entity below. 
Greg\PropertyBundle\Entity\Property:
    properties:
        property_id:
            - NotBlank: ~
            - Type:
                type: string
        addresses:
            - All:
                - Type:
                    type: Greg\PropertyBundle\Entity\Address
            # addresses is array of entities, so use "traverse" option to validate each entity in that array
            - Valid: { traverse: true }

# child entity
Greg\PropertyBundle\Entity\Address:
    properties:
        city:
            - NotBlank: ~
            - Type:
                type: string

More details about "Valid" constraint you can find here: http://symfony.com/doc/current/reference/constraints/Valid.html

QArea
  • 4,955
  • 1
  • 12
  • 22
  • Thank you it worked great for me. If you have just one address (a property that references an object, not an array of objects), then you can also do: - Valid: ~ (without the traverse option). – Daniel May 03 '15 at 00:43