Symfony2+Doctrine - Validating one-to-many collection of entities

后端 未结 4 711
一整个雨季
一整个雨季 2020-12-29 09:33

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

相关标签:
4条回答
  • 2020-12-29 10:00

    Just add annotation assert like following

    /** 
     * @Assert\Count(
     *      min = "1",
     *      minMessage = "You must specify at least one"
     * )
     * @Assert\Valid 
     * 
     */
    protected $name_of_collection_property;
    
    0 讨论(0)
  • 2020-12-29 10:03

    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

    0 讨论(0)
  • 2020-12-29 10:22

    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;
    
    0 讨论(0)
  • 2020-12-29 10:25

    I had the same problem but was solved with:

    /**
     * @ORM\OneToMany(
     *  targetEntity="Entity",
     *  mappedBy="mappedEntity",
     *  cascade={"persist" , "remove"}
     * )
     * @Assert\Valid
     */
    
    0 讨论(0)
提交回复
热议问题