0

I'm performing validation on an entity property using a custom constraint, but my forms are using setters and getters that don't correspond directly to the validating field, but affect it.

What I want to do is hook the validation errors on to the form field that originally handled the invalid user input.

Here's a much simplified example of the validating property and the setter method that the form binds to:

/* @Assert\ValidFoo */ 
private $foo;

public function setFooBar( $baz ){
    $this->foo->bar = $baz;
}

In my Twig template I want to be able to display the error with:

{{ form_errors(form.foobar) }}

I can dump out any errors at the end of the form with {{form_errors(form)}} but that's no good for my purposes. How can I alias the validation error onto the specific form field I want?


Update:

I've tried using addViolationAt as answered here but it's not working for me. Possibly because the property path doesn't really exist?

5
  • Why you not use a Validation Callback? Commented Sep 12, 2014 at 6:53
  • My validation callback is in the class property validator. It works, but the form doesn't know how to re-map the errors onto its fields. Are you suggesting I execute a validator with a callback directly in my form handling or in my form Type object? Commented Sep 12, 2014 at 8:41
  • Maybe I don't understand clearly but if you can't add the error in you controller (or in your formHandler class) like this: if (!callback) $form->get('yourField')->addError(new FormError('error message')); you can map the error callback directly to the field you want in your formType like this: $resolver->setDefaults(array('error_mapping' => array('yourCallback' => 'fieldYouWant'))); Commented Sep 12, 2014 at 10:38
  • Yes! error_mapping was the key. Thanks. I'll accept your answer if you add one. Commented Sep 12, 2014 at 18:46
  • glad to be helpful :-) Commented Sep 12, 2014 at 18:51

1 Answer 1

1

You can map the error callback directly to the field you want in your formType like this:

$resolver->setDefaults(array( 'error_mapping' => array( 'yourCallback' => 'fieldYouWant' ) ) );

Sign up to request clarification or add additional context in comments.

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.