3

我自己使用 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

要调用验证器,我将使用 DI 将其传递给我的一项服务并执行以下操作:

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

我还通过传入以下标志进行了尝试:

$errorList = $this->validator->validate($data, null, true, true);
4

1 回答 1

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

有关“有效”约束的更多详细信息,您可以在此处找到:http: //symfony.com/doc/current/reference/constraints/Valid.html

于 2013-05-14T08:08:30.963 回答