Symfony: get errors from Validator & Form components

This is a nice snippet to better format symfony errors on forms and validator:

private function getErrorsFromvalidator(ConstraintViolationListInterface $errors)
{
$formattedErrors = [];
foreach ($errors as $error) {
$formattedErrors[$error->getPropertyPath()] = $error->getMessage();
}

return $formattedErrors;
}

private function getErrorsFromForm(FormInterface $form)
{
$errors = array();
foreach ($form->getErrors() as $error) {
$errors[] = $error->getMessage();
}
foreach ($form->all() as $childForm) {
if ($childForm instanceof FormInterface) {
if ($childErrors = $this->getErrorsFromForm($childForm)) {
$errors[$childForm->getName()] = $childErrors;
}
}
}

return $errors;
}

Usage for validator errors:

/** @var \Symfony\Component\Validator\ConstraintViolationListInterface */
$errors = null;

$errors = $this->validator->validate($review);
$this->getErrorsFromvalidator($errors)

Usage for form errors:
$this->getErrorsFromForm($form)

Leave a Comment

Your email address will not be published. Required fields are marked *