I've set a constraint on a class member variable using an annotation:
/* @Assert\Length(min="3") */
protected $password;
This constraint is added to a form built in a form class when I add a field corresponding to this variable without specifying its type:
$builder->add('password');
The type is guessed as "text". But, I want the input type of this field to be "password". But when I specify this type like this:
$builder->add('password', 'password');
The constraint in the annotation is not added.
I know that I can add the constraint to the field in the form class:
$builder->add('password', 'password',
array('constraints' => new Assert\Length(array('min' => 3))))
Or I could use JavaScript to change the input type of the field from text to password.
But, I feel I should be able to inject the annotated constraints into the form whilst also specifying the type of the field. I imagine that this must be a common problem. What have I missed?
You don't need set constraints in form type to validate your class. First check your annotation, it must start with double "*" .
To generate the form, you should add in your form type the method 'setDefaultOptions' with 'data_class' attribute:
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'XXX\YourBundle\Entity\YourEntity',
'id' => null
));
}
Data will be validated with the constraints defined in your class
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.