I've a password
表单字段(not映射到User
密码)与其他两个(映射)字段一起用于更改密码表单,first
and last
.
我必须动态添加验证器:如果值密码为空则不进行验证应该发生。否则一个新的MinLength
and MaxLength
应该添加验证器.
这是我到目前为止所做的:创建重复的password
字段,添加一个CallbackValidator
and return
if $form->getData()
is null
.
那么,如何向 $field 添加最小和最大长度的验证器?
哦,好吧,经过几次实验,我自己找到了解决方案。
我将在几天内不回答这个问题,因为人们可以发布更好的解决方案,那真是太受欢迎了:)
特别是,我发现了new FormError
部分redundat,不知道是否有更好的方法将错误添加到表单中。老实说,不知道为什么new Form\CallbackValidator
工作同时new CallbackValidator
won't.
所以,不要忘记添加use
像这样的声明:
use Symfony\Component\Form as Form, // Mendatory
Symfony\Component\Form\FormInterface,
Symfony\Component\Validator\Constraints\MinLength,
Symfony\Component\Validator\Constraints\MinLengthValidator;
回调是:
$validation = function(FormInterface $form) {
// If $data is null then the field was blank, do nothing more
if(is_null($data = $form->getData())) return;
// Create a new MinLengthValidator
$validator = new MinLengthValidator();
// If $data is invalid against the MinLength constraint add the error
if(!$validator->isValid($data, new MinLength(array('limit' => 3)))) :
$template = $validator->getMessageTemplate(); // Default error msg
$parameters = $validator->getMessageParameters(); // Default parameters
// Add the error to the form (to the field "password")
$form->addError(new Form\FormError($template, $parameters));
endif;
};
好吧,这是我无法理解的部分(为什么我被迫以前缀Form
),但没关系:
$builder->get('password')->addValidator(new Form\CallbackValidator($validation));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)