1

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
  • can you please share your twig code? Commented Feb 22, 2013 at 15:29

2 Answers 2

4

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!');
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

That works, thank you. Why [date_of_birth], not only the ID of field (i.e. date_of_birth) ?
1

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().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.