I'm new on Symfony2 world. I was trying to learn the basics of Validation in Symfony2 when I ran into a problem with it. According to the guide, to manage properly a sequence of validation groups you have to add this annotation's line on your Entity
class:
/** * @Assert\GroupSequence({"User", "Strict"}) */
And put some annotation wherever you want to handle the proper rule. In my case as well as one of the guide is the password
field that should be valid only if firstly it has compiled (and respects my rules such as minimum length) and then if is different from username
value. The problem is it doesnt' work for me!
I mean, I have the same User
class and I used the same form of their example:
$form = $this->createFormBuilder($user, array('validation_groups' => array('signup','strict'))) ->add('name', 'text') ->add('email', 'text') ->add('password', 'password') ->add('signup', 'submit') ->getForm();
Here's my User
class:
<?php namespace XXX\SiteBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; /** * User * * @ORM\Table(name="users") * @ORM\Entity * @Assert\GroupSequence({"User", "signup", "strict"}) */ class User { //.. /** * @var string * * @ORM\Column(name="name", type="string", length=255) * @Assert\NotBlank(groups={"signup"}) * @Assert\Length(min=3,groups={"signup"}) */ private $name; /** * @var string * * @ORM\Column(name="password", type="string", length=255) * @Assert\NotBlank(groups={"signup"}) * @Assert\Length(min=7,groups={"signup"}) */ private $password; /** * @var string * * @ORM\Column(name="email", type="string", length=255) * @Assert\NotBlank(groups={"signup"}) * @Assert\Email(checkMX=true, groups={"signup"}) */ private $email; /** * @Assert\True(groups={"strict"}) */ public function isPasswordLegal() { return $this->name != $this->password; } //..some getter\setter methods }
When I submit the form without putting values in the fields it shows me every error (and that's right) but also one that isPasswordLegal()
launches, even BEFORE the others!
What am I missing? Thank you all!
The reason why the error is displayed before the others is, that you use it as a method validator and Symfony assigns the error message to the form instance and not the form field.
Edit:
All forms provide the error_mapping
option which lets you define where the error messages should be shown.
In your case it would look like this:
$options = array( 'validation_groups' => array('signup','strict'), 'error_mapping' => array( 'isPasswordLegal' => 'password', ), ); $form = $this->createFormBuilder($user, $options) ->add('name', 'text') ->add('email', 'text') ->add('password', 'password') ->add('signup', 'submit') ->getForm();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With