我需要一个简单的表格来注册用户。表单验证按预期工作,但由于某种原因,来自回调约束的验证错误显示两次。
我在错误消息中插入了一个随机数,以查看回调是否被调用了一次或两次。 2条错误消息显示相同的随机数,因此回调(可能)只调用一次。
非常感谢任何帮助!
额外问题:"回调函数中的所有错误都显示在表单中的相同位置(如预期的那样)。 (轻松)是否可以指定应该显示验证错误的字段? "
表单类型类如下所示:
class RegisterType extends AbstractType{
static private $em;
static private $translator;
public function __construct( EntityManager $em , TranslatorInterface $translator){
RegisterType::$em = $em;
RegisterType::$translator = $translator;
}
public function buildForm(FormBuilderInterface $builder , array $options){
$builder
->add('email','email',[
'attr'=>['placeholder'=>RegisterType::$translator->trans('your.email')],
'label'=>false ,
'constraints'=>[new NotBlank() , new Assert\Email()]])
->add('password','password',[
'attr'=>['placeholder'=>RegisterType::$translator->trans('your.password')],
'label'=>false ,
'constraints'=>[new NotBlank()]])
->add('confirmPassword','password',[
'attr'=>['placeholder'=>RegisterType::$translator->trans('confirm.password')],
'label'=>false ,
'constraints'=>[new NotBlank()]]);
}
public function getName(){
return 'register';
}
public function configureOptions( OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'constraints' =>array( new Assert\Callback( array('AppBundle\Forms\Type\RegisterType','validateForm' ) )),
));
}
static public function validateForm(array $data, ExecutionContextInterface $context){
if($data['email']){
$user = RegisterType::$em->getRepository('AppBundle:User')->findByEmail($data['email']);
if($user){
$context->buildViolation('email.is.used'.rand())->addViolation();
}
}
if($data['password'] && $data['confirmPassword']){
if($data['password'] != $data['confirmPassword']){
$context->buildViolation('password.confirm.failed')->addViolation();
}
}
}
在控制器中调用表单如下:
public function registerFormAction(Request $request){
$form = $this->createForm('register');
$form->handleRequest($request);
if($form->isValid()){
//TODO
}
return new JsonResponse(['success'=>false,
'message'=>$this->renderView('AppBundle:Security:register.html.twig' , ['form'=>$form->createView()])
]);
}
用于呈现表单的树枝模板是:
{% form_theme form _self %}
{%- block form_row -%}
<div class = "form-group">
{{- form_errors(form) -}}
{{- form_widget(form) -}}
</div>
{%- endblock form_row -%}
{{ form(form) }}
答案 0 :(得分:4)
您正在显示表单错误和表单小部件两次!
你有
<div class = "form-group">
{{- form_errors(form) -}} //displays all form errors
{{- form_widget(form) -}} //displays all form widgets (not the labels!)
</div>
和
{{ form(form) }} //displays the whole form
你的代码中的。
为什么不自己渲染表单,然后还可以设置表单错误的显示位置。
{{ form_start(form) }}
<div class="form-group">
{{ form_errors(form.username) }} //errors for the "username" field of your form
{{ form_label(form.username) }} //labels for the "username" field of your form
{{ form_widget(form.username) }} //formfields for the "username" field of your form
</div>
{{ form_end(form) }}
此外,还有一个名为form_rest(form)
的树枝函数,它将显示所有尚未手工渲染的表单字段!
答案 1 :(得分:1)