I\'m using Symfony2 forms to validate POST and PUT requests to an API. The form handles binding the request data to the underlying entity and then validating the entity. Eve
I needed a solution to get an associative array of all errors of all nested forms with the key formated so it represents the document id of the corresponding form field element:
namespace Services;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormErrorIterator;
/**
* Class for converting forms.
*/
class FormConverter
{
/**
* Gets all errors of a form as an associative array with keys representing the dom id of the form element.
*
* @param Form $form
* @param bool $deep Whether to include errors of child forms as well
* @return array
*/
public function errorsToArray(Form $form, $deep = false) {
return $this->getErrors($form, $deep);
}
/**
* @param Form $form
* @param bool $deep
* @param Form|null $parentForm
* @return array
*/
private function getErrors(Form $form, $deep = false, Form $parentForm = null) {
$errors = [];
if ($deep) {
foreach ($form as $child) {
if ($child->isSubmitted() && $child->isValid()) {
continue;
}
$iterator = $child->getErrors(true, false);
if (0 === count($iterator)) {
continue;
} elseif ($iterator->hasChildren()) {
$childErrors = $this->getErrors($iterator->getChildren()->getForm(), true, $child);
foreach ($childErrors as $key => $childError) {
$errors[$form->getName() . '_' . $child->getName() . '_' .$key] = $childError;
}
} else {
foreach ($iterator as $error) {
$errors[$form->getName() . '_' . $child->getName()][] = $error->getMessage();
}
}
}
} else {
$errorMessages = $this->getErrorMessages($form->getErrors(false));
if (count($errorMessages) > 0) {
$formName = $parentForm instanceof Form ? $parentForm->getName() . '_' . $form->getName() : $form->getName();
$errors[$formName] = $errorMessages;
}
}
return $errors;
}
/**
* @param FormErrorIterator $formErrors
* @return array
*/
private function getErrorMessages(FormErrorIterator $formErrors) {
$errorMessages = [];
foreach ($formErrors as $formError) {
$errorMessages[] = $formError->getMessage();
}
return $errorMessages;
}
}