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:
<?php | |
public function getAllErrors($children, $template = true) { | |
$this->getAllFormErrors($children); | |
return $this->allErrors; | |
} | |
private function getAllFormErrors($children, $template = true) { | |
foreach ($children as $child) { | |
if ($child->hasErrors()) { | |
$vars = $child->createView()->getVars(); | |
$errors = $child->getErrors(); | |
foreach ($errors as $error) { | |
$this->allErrors[$vars["name"]][] = $this->convertFormErrorObjToString($error); | |
} | |
} | |
if ($child->hasChildren()) { | |
$this->getAllErrors($child); | |
} | |
} | |
} | |
private function convertFormErrorObjToString($error) { | |
$errorMessageTemplate = $error->getMessageTemplate(); | |
foreach ($error->getMessageParameters() as $key => $value) { | |
$errorMessageTemplate = str_replace($key, $value, $errorMessageTemplate); | |
} | |
return $errorMessageTemplate; | |
} |
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:
<?php | |
foreach($form->getErrors() as $e) | |
$errors[]=$translator->trans($this->convertFormErrorObjToString($e), array(), 'validators'); | |
foreach($this->getAllErrors($children) as $key=>$error) | |
$errors[]=$key.': '.$translator->trans($error[0], array(), 'validators'); |
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’).