Reputation: 173
I have a ProjetContact
entity that have a roles
relation. A ProjetContact entity must have at least one role. So I added a Count constraint as annotation.
/**
* @var Collection
*
* @Assert\Count(min=1, minMessage="Vous devez sélectionner au moins un rôle par contact")
*
* @ORM\ManyToMany(targetEntity="ContactRole")
* @ORM\JoinTable(
* name="projet_contact_role",
* joinColumns={
* @ORM\JoinColumn(name="projet_contact_role_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(name="role_id", referencedColumnName="id")
* }
* )
*/
private $roles;
But, this doesn't work, the constraint is ignored. A user can submit a form without selecting any role.
I found that if I configure the validator on the form builder, it works.
$builder
->add('roles', 'entity', array(
'label' => 'Rôles',
'class' => 'MyIntranetBundle:ContactRole',
[...]
'constraints' => new Count(
array('min'=>1, 'minMessage'=>'Vous devez sélectionner au moins un rôle par contact')
)
))
->[...]
I would prefer configuring my validator directly on my entity. Why this doesn't work that way?
Upvotes: 1
Views: 84
Reputation: 173
I had to add @Assert\Valid()
on the parent entity that use ProjetContact
.
/**
* @var Collection
*
* @Assert\Valid()
*
* @ORM\OneToMany(targetEntity="ProjetContact", mappedBy="projet", cascade={"persist","remove"})
*/
private $contacts;
Upvotes: 0
Reputation: 1814
Two possible causes:
Assert
correctly in your entity definition (should be use Symfony\Component\Validator\Constraints as Assert;
)Default
group.Upvotes: 1