Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
795 views
in Technique[技术] by (71.8m points)

symfony - Custom constraint validation error doesn't display next to field in Symfony2

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?

EDIT:

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> 

At the begining of the form I also have:

<div class="grid_8">
  {{form_errors(form)}}
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!');
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...