MrGlass MrGlass - 2 months ago 8
PHP Question

Adding a field specific error from the controller in symfony2

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");

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?


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");

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;