Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
793 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...