Symfony 3 and newer
I recently made a function which creates a tree of form errors. This will be helpful for returning list of errors back to front-end. This is based on form types having:
'error_bubbling' => false
Code:
public static function getFormErrorsTree(FormInterface $form): array
{
$errors = [];
if (count($form->getErrors()) > 0) {
foreach ($form->getErrors() as $error) {
$errors[] = $error->getMessage();
}
} else {
foreach ($form->all() as $child) {
$childTree = self::getFormErrorsTree($child);
if (count($childTree) > 0) {
$errors[$child->getName()] = $childTree;
}
}
}
return $errors;
}
Output:
Array
(
[name] => Array
(
[0] => This value is not valid.
)
[emails] => Array
(
[0] => Array
(
[0] => Given e-mail is not valid.
[1] => Given e-mail is not valid #2.
)
[1] => Array
(
[0] => Given e-mail is not valid.
[1] => Given e-mail is not valid #2.
)
)
)
Notice: I know that errors from deeper level fields can be overwritten if higher level has errors, but this is on purpose for my usage.