Francis
Francis

Reputation: 173

Why my constraint validation works when declared on the form builder but got ignored when configured on my entity?

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

Answers (2)

Francis
Francis

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

Konstantin Pereiaslov
Konstantin Pereiaslov

Reputation: 1814

Two possible causes:

  1. You didn't import Assert correctly in your entity definition (should be use Symfony\Component\Validator\Constraints as Assert;)
  2. You have validation groups defined for the form, and didn't include Default group.

Upvotes: 1

Related Questions