Symfony子实体仅被验证为Type,跳过它自己的验证

gre*_*reg 3 symfony symfony-2.2

我正在使用Symfony Validator,没有表单组件.

我有一个包含子实体的实体,目前我可以验证该字段是子实体的实例,但我还需要它来验证子实例的约束.

#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
Run Code Online (Sandbox Code Playgroud)

要调用验证器,我将DI传递给我的一个服务并执行此操作:

// Validate the data
$errorList = $this->validator->validate($data);
Run Code Online (Sandbox Code Playgroud)

我也通过传递以下标志来尝试它:

$errorList = $this->validator->validate($data, null, true, true);
Run Code Online (Sandbox Code Playgroud)

QAr*_*rea 7

默认情况下,不会为属性中的对象委派验证.如果要调用子对象的验证过程,则应使用特定约束"有效".

所以你的验证脚本将是:

#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
Run Code Online (Sandbox Code Playgroud)

有关"有效"约束的更多详细信息,请访问:http: //symfony.com/doc/current/reference/constraints/Valid.html