OneToMany相关实体的UniqueEntity验证

时间:2014-10-22 20:25:04

标签: validation symfony doctrine constraints one-to-many

我为ProductType, ProductTypeAttributes(OneToMany)定义了以下验证:

Bike\ProductBundle\Entity\ProductType:
    properties:
        name:
            - NotBlank: ~
        productTypeAttributes:
            - Valid: ~
Bike\ProductBundle\Entity\ProductTypeAttribute:
    constraints:
        - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity:
            fields: [attribute, productType]
            errorPath: attribute
            message: 'Attributes must be different for the same product type.'

ProductTypeAttributes有一个唯一的密钥:attribute,productType

我正在使用ProductTypeAttributes的嵌入表单(集合类型),可以添加/删除项目。验证似乎仅适用于数据库中已存在的记录,只有在我添加一个新的相关实体时才会发生,这将触发记录的唯一密钥违规。

问题是当添加两个具有相同属性/ productType的全新相关实体时,验证不起作用。在这种情况下,我得到了#34;重复的条目"异常。

因此,验证仅使用默认的findBy方法检查db记录,但不会针对重复项对新添加的记录进行检查。

有什么办法可以克服这个问题?

1 个答案:

答案 0 :(得分:0)

是,但不是通过默认的UniqueEntity验证器。您必须手动创建第二个验证器,该验证器适用于整个ProductType实体,并验证所有新(未保存)属性都不相同。

查看Symfony的烹饪手册,了解如何制作自己的验证器: http://symfony.com/doc/current/cookbook/validation/custom_constraint.html

相关问题