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

跟風遠走 提交于 2019-11-28 10:45: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?

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>

回答1:


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



回答2:


You can add the violation to one particular field with addViolationAtSubPath() instead of the classic addViolation() used in the validator. You can have a look at the method definition here.

An example

Lets take the example of a validator that need to validate that the username property is alphanumeric:

class ContainsAlphanumericValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        if (!preg_match('/^[a-zA-Za0-9]+$/', $value, $matches)) {
            $this->context->addViolationAtSubPath('username',$constraint->message, array('%string%' => $value));
        }
    }
}

Edit

You can also take a look at addViolationAtPath() and addViolationAt().



来源:https://stackoverflow.com/questions/15027491/custom-constraint-validation-error-doesnt-display-next-to-field-in-symfony2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!