Recently I was working on an API call which uses a form to validate the data you are passing in. I ran into the issue of getting all the errors for a form in Symfony2 is not as straight forward as you would think. At first I tried `$form->getErrors()` and then looped through the errors. That didn’t get all of them. After looking around I found:

This works really well for any errors which are bound to a field. However it will not catch global errors such as a unique validator. It should probably be renamed from getAllErrors(). In order to get those you need to also loop through $form->getErrors(). This was returning the global errors only for me. Here is my code in the end:

There may be a better way, just wanted to shoot this out as not many people had good solutions on it.

Bonus: If you are using the translator service on validators and you get an error which is the ‘validators’ translation files, make sure you use the proper domain, ie: $translator->trans(‘key’,array(),’validators’).

  • Afonso Vaz

    Thank you for this.

    Going to try it now :)

  • http://www.boxlightmedia.com Robert Cambridge

    This will give you all the error messages of a form (including global errors):

    private function getAllFormErrorMessages($form) {
    $retval = array();
    if ($form->hasErrors()) {
    foreach ($form->getErrors() as $error) {
    $retval[] = $error->getMessage();
    }
    }
    foreach ($form->all() as $name => $child) {
    $retval[$name] = $this->getAllFormErrors($child);
    }

    return $retval;
    }

  • Jeremy Cook

    Thanks for this. I’ve been running into a similar problem where I want to use a form object to POST and PUT requests to an API. I collect any form errors to display in a JSON response to a bad POST or PUT request. Is there any way to get the name of the field that caused the error from a global form error? This would make my error messages a lot better!

  • http://www.boxlightmedia.com Robert Cambridge

    @Jeremy Cook: the whole point of global errors is that they’re not associated with a field.

    If you’re generating the errors, you should associate them with a field at that point.

  • Matt Daum

    @Jeremy I agree with Robert. If you aren’t throwing truly global errors you should be associating them with a field in which case you’ll be able to get a better formatted message.