Skip to content

Instantly share code, notes, and snippets.

@b-b3rn4rd
Last active August 29, 2015 14:05
Show Gist options
  • Save b-b3rn4rd/87a83cad876edc1fc2f0 to your computer and use it in GitHub Desktop.
Save b-b3rn4rd/87a83cad876edc1fc2f0 to your computer and use it in GitHub Desktop.
Symfony2 - get form errors as a flat array
<?php
namespace Interprac\Bundle\UtilityBundle\Form;
use Symfony\Component\Form\Form;
class FormErrors
{
public function getArray(Form $form, $style = 'KO')
{
$method = sprintf('get%sErrors', $style);
$messages = $this->$method($form->all());
return $messages;
}
private function getKOErrors(Form $children)
{
$errors = array();
/* @var $child \Symfony\Component\Form\Form */
foreach ($children as $child) {
$type = $child->getConfig()->getType()->getName();
if ($child->count() && ($type !== 'choice')) {
$childErrors = $this->getKOErrors($child->all());
if (sizeof($childErrors)) {
$errors = array_merge($errors, $childErrors);
}
} else {
if (!$child->isValid()) {
// I need only one error message per field
$errors[$child->getName()] = $child->getErrors()->current()->getMessage();
}
}
}
return $errors;
}
}
@b-b3rn4rd
Copy link
Author

  • warning: it won't work if you are extending a choice type

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment