自定义约束验证错误不会显示在Symfony2中的字段旁边 [英] Custom constraint validation error doesn't display next to field in Symfony2

查看:160
本文介绍了自定义约束验证错误不会显示在Symfony2中的字段旁边的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的Symfony2项目中使用FOSUserBundle。我在用户实体中添加了生日字段,因为它在注册表单中需要。我还在注册表中添加了一个正确的字段(type = birthday)。我必须检查用户的年龄是否超过18.我为此准备了自己的约束本教程。一切工作完美,但错误消息附加到形式不是字段,我想要错误消息旁边的字段。相反,我得到它的整个形式。格式中的每个其他错误都显示在正确的字段旁边。有人知道如何强制约束附加到字段,而不是形式?

I am using FOSUserBundle in my Symfony2 project. I added 'birthday' field in User entity, because it is required in registration form. I also added a proper field (type=birthday) to the registration form. I have to check if age of a user is above 18. I prepared my own Constraint for this following this tutorial. Everything works perfectly, but error message is attached to form not to field, and I want error message next to field. Instead I get it above the whole form. Every other error in form is displayed next to a proper field. Does anybody know how to force constraint to be attached to the field, not to the form?

编辑:

Twig代码片段,呈现此特定字段:

Twig code fragment which renders this particular field:

<div class="grid_8" style="margin-bottom:20px;">
      <div class="grid_2 alpha">{{ form_label(form.date_of_birth)}}</div>
      <div class="grid_4">{{ form_widget(form.date_of_birth)}}</div>
      <div class="grid_2 omega">{{ form_errors(form.date_of_birth)}}</div>
</div> 

在表单开头,我还有:

<div class="grid_8">
  {{form_errors(form)}}
</div>


推荐答案

如果您将回调附加到表单,你应该设置属性路径有点不同的方式:

If you attach callback to form – not to particular field, you should set property path a bit different way:

public function isFormValid($data, ExecutionContext $context)
{
    if ( $condition == false ) {
        $context->addViolationAt('[date_of_birth].date_of_birth', 'You are too young!');
    }
}

这篇关于自定义约束验证错误不会显示在Symfony2中的字段旁边的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆