Symfony2约束实体验证yml

时间:2014-09-22 09:44:36

标签: validation symfony entity type-constraints

我有很多关系(用户和帐户)。在用户实体中,我有私有属性组(数组集合)。

当我尝试使用简单的“NotBlank”验证此属性(组)时,它不起作用。所以我在下面尝试这个(集合和选择)。

我读了这个http://symfony.com/fr/doc/2.3/reference/constraints/Choice.html 这个http://symfony.com/fr/doc/2.3/reference/constraints/Collection.html但它没有用,或者我没有正确使用它们。

有人可以给我一些帮助吗?

/* USER accounts property 

...

/**
 * @ORM\ManyToMany(targetEntity="Account", mappedBy="users", cascade={"persist", "remove"})
 */
 private $accounts;

...

比userType

...
->add('accounts', 'genemu_jqueryselect2_entity', array(
                    "class"         => "CMiNewsBundle:Account",
                    "property"      => "name",
                    "multiple"      => "true",
                    "query_builder" => function (EntityRepository $er) use ($user)
                    {
                          return $er->createQueryBuilder('acc')
                                    ->join('acc.users','u')
                                    ->where('u.id = :userID')
                                    ->setParameter('userID' , $user);
                    }
                    )
)
...

validation.yml

CM\Bundle\iNewsBundle\Entity\User:
    properties:

        ...

        accounts:
            - NotBlank: ~

        ...

1 个答案:

答案 0 :(得分:2)

" NotBlank"断言检查属性是否=== null ||财产===''。由于您的属性是一个集合,您可能在构造函数中将其初始化为ArrayCollection,因此它永远不会为null。

对于收藏品,你应该使用" Count"断言

http://symfony.com/doc/current/reference/constraints/Count.html

它强制你设置"最大值"计数和最小值,因此您可能想要创建自己的断言。