-
-
Save Graceas/6505663 to your computer and use it in GitHub Desktop.
class FormErrorsSerializer { | |
public function serializeFormErrors(\Symfony\Component\Form\Form $form, $flat_array = false, $add_form_name = false, $glue_keys = '_') | |
{ | |
$errors = array(); | |
$errors['global'] = array(); | |
$errors['fields'] = array(); | |
foreach ($form->getErrors() as $error) { | |
$errors['global'][] = $error->getMessage(); | |
} | |
$errors['fields'] = $this->serialize($form); | |
if ($flat_array) { | |
$errors['fields'] = $this->arrayFlatten($errors['fields'], | |
$glue_keys, (($add_form_name) ? $form->getName() : '')); | |
} | |
return $errors; | |
} | |
private function serialize(\Symfony\Component\Form\Form $form) | |
{ | |
$local_errors = array(); | |
foreach ($form->getIterator() as $key => $child) { | |
foreach ($child->getErrors() as $error){ | |
$local_errors[$key] = $error->getMessage(); | |
} | |
if (count($child->getIterator()) > 0) { | |
$local_errors[$key] = $this->serialize($child); | |
} | |
} | |
return $local_errors; | |
} | |
private function arrayFlatten($array, $separator = "_", $flattened_key = '') { | |
$flattenedArray = array(); | |
foreach ($array as $key => $value) { | |
if(is_array($value)) { | |
$flattenedArray = array_merge($flattenedArray, | |
$this->arrayFlatten($value, $separator, | |
(strlen($flattened_key) > 0 ? $flattened_key . $separator : "") . $key) | |
); | |
} else { | |
$flattenedArray[(strlen($flattened_key) > 0 ? $flattened_key . $separator : "") . $key] = $value; | |
} | |
} | |
return $flattenedArray; | |
} | |
} |
Thanks for this, works great !
Thanks for the code! I know this is now dated, consider using Symfony\Component\Form\FormInterface instead. Everything seems to be working fine with that small edit on 2.6.
Good job :)
Tested on symfony 2.8
+1 for the Symfony\Component\Form\FormInterface usage. It solved my issues.
Nice little script, tested on 3.0.2 and works but it through an exception when the submit button came into the foreach so I had to make sure that wasn't serialized.
private function serialize(\Symfony\Component\Form\Form $form)
{
$local_errors = array();
foreach ($form->getIterator() as $key => $child) {
foreach ($child->getErrors() as $error){
$local_errors[$key] = $error->getMessage();
}
if (count($child->getIterator()) > 0) {
if (!$child instanceof \Symfony\Component\Form\SubmitButton) {
$local_errors[$key] = $this->serialize($child);
}
}
}
return $local_errors;
}
Great for simply returning the template error string to the view via AJAX. +1
it does not return dates and choices in radio in the serialized response
Updated version of this to keep all the error properties intact. Added an unserializer to apply the errors back to the form if you intend to store the errors into a database or cache.
https://gist.github.com/linxlad/3ec76c181f717fba532bf43484b7c970
In action you may use: