Symfony2+Doctrine - Validating one-to-many collect

2019-02-03 08:04发布

I have a form to create a new entity. That entity has a collection of other entities that are also entered in that form.

I want to use the validation options of the entity in the collection to validate those entities but it does not work. The validation rules of the "main" entity (Person) are checked, but the validation rules of the entities in the addressList collection (Address) are not checked. When I input invalid information in the fields, the submitted form is successfully validated.

In this example, the annotation for street is not used on validation.

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;

    ...

}

How can I get the form to validate the supplied Address entities?

4条回答
beautiful°
2楼-- · 2019-02-03 08:14

You could also use the "Valid" constraint with the "All" constraint :

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

protected $addressList;
查看更多
你好瞎i
3楼-- · 2019-02-03 08:15

I use this:

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

查看更多
叛逆
4楼-- · 2019-02-03 08:26

Just add annotation assert like following

/** 
 * @Assert\Count(
 *      min = "1",
 *      minMessage = "You must specify at least one"
 * )
 * @Assert\Valid 
 * 
 */
protected $name_of_collection_property;
查看更多
Deceive 欺骗
5楼-- · 2019-02-03 08:30

I had the same problem but was solved with:

/**
 * @ORM\OneToMany(
 *  targetEntity="Entity",
 *  mappedBy="mappedEntity",
 *  cascade={"persist" , "remove"}
 * )
 * @Assert\Valid
 */
查看更多
登录 后发表回答