Symfony2 + Doctrine - 验证一对多实体集合

时间:2012-05-02 09:09:41

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

我有一个表单来创建一个新实体。该实体还有一组其他实体也以该形式输入。

我想使用集合中实体的验证选项来验证这些实体,但它不起作用。检查“主”实体(Person)的验证规则,但不检查addressList集合(地址)中实体的验证规则。当我在字段中输入无效信息时,已成功验证提交的表单。

在此示例中,街道的注释不用于验证。

class Person 
{
    ...

    /**
     * @ORM\OneToMany(targetEntity="Address", mappedBy="owner", cascade={"persist", "detach"})
     */
    protected $addressList;

    ....
}

class Address
{
    ...
    /**
     * @ORM\ManyToOne(targetEntity="Person", inversedBy="addressList")
     * @ORM\JoinColumn(name="person_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $owner;

    /**
     * @ORM\Column(type="string", length=75)
     * @Assert\MinLength(
     *     limit=3,
     *     message="Street must have atleast {{ limit }} characters."
     * )
     */
    protected $street;

    ...

}

如何获取表单以验证提供的地址实体?

4 个答案:

答案 0 :(得分:15)

我有同样的问题,但解决了:

/**
 * @ORM\OneToMany(
 *  targetEntity="Entity",
 *  mappedBy="mappedEntity",
 *  cascade={"persist" , "remove"}
 * )
 * @Assert\Valid
 */

答案 1 :(得分:7)

我用这个:

use Symfony\Component\Validator\ExecutionContextInterface;

class Person 
{
...

/**
 * @ORM\OneToMany(targetEntity="Address", mappedBy="owner", cascade={"persist", "detach"})
 */
protected $addressList;

....

/**
 * @Assert\Callback
 */
public function validate(ExecutionContextInterface $context)
{
    if (!$this->getAddressList()->count()) {
        $context->addViolationAt(
            'addressList',
            'You must add at least one address',
            array(),
            null
        );
    }
}
}

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

答案 2 :(得分:5)

只需添加注释断言,如下面的

/** 
 * @Assert\Count(
 *      min = "1",
 *      minMessage = "You must specify at least one"
 * )
 * @Assert\Valid 
 * 
 */
protected $name_of_collection_property;

答案 3 :(得分:0)

您还可以将“Valid”约束与“All”约束一起使用:

/**
 * @ORM\OneToMany(targetEntity="Address", mappedBy="owner", cascade={"persist", "detach"})
 * @Assert\All({
 *     @Assert\Valid
 * })
 */

protected $addressList;