Search code examples
symfonysymfony-validator

How to create constraint for limiting max childs


Let's say I have two entities Bus and People with a relation OneToMany between them. Bus can hold a maximum of 10 persons.

How to create a constraint to control this?

For example:

* @MyAssert\ParentMaxChild(max=10)

* @ORM\ManyToOne(targetEntity="Webface\CharacterBundle\Entity\Bus", inversedBy="wac")
* @ORM\JoinColumn(name="bus_id", referencedColumnName="id", nullable=false)

private $bus;

Solution

  • Use the Count constraint.

    In your Bus class, add the constraint in the Person annotation:

    /**
     * ... Rest of the annotation ...
     * @Assert\Count(
     *      max = "10",
     *      maxMessage = "Bus can hold a maximum of 10 persons."
     * )
     */
    protected $persons;
    

    Note that you can specify a min parameter and the according message.