30

I have some complex validation going on with my symfony form, and I need to be able to assign an error to a specific field from my controller. Right now, I have global errors working like this:

$error = new formerror("There is an error with the form");
$form->addError($error);

But that creates a global error, not one bound to a specific field.

Is there a way to throw an error on a specific field from my controller?

1 Answer 1

60

Thanks to some help over IRC (thanks @fkrauthan!) I came up with an answer.

Every field in SF2 is actually an instance of form. What you need to do is access the form object of the field, and add then error onto it. Thankfully, symfony provides a method to get an embedded form/field.

Heres my code:

$error = new FormError("There is an error with the field");
$form->get('field')->addError($error);

As some people have pointed out, you will need to include the FormError class at the top of your file: use Symfony\Component\Form\FormError;

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

7 Comments

Stack overflow doesn't let you accept your own answer for the first 2 days.
what do I need to include as a USE on top in order to be able to use formerror class properly?
You don't actaully need to use the 'use' statement. You just need to pass the full qualifier after new. $error = new \Symfony\Component\Form\FormError("There is an error with the field");
This is still true for Symfony 4 in 2019
@Chris The controller will continue, but the form should now be marked invalid.
|

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.