Last active
August 29, 2015 14:05
-
-
Save b-b3rn4rd/87a83cad876edc1fc2f0 to your computer and use it in GitHub Desktop.
Symfony2 - get form errors as a flat array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
Author
b-b3rn4rd
commented
Aug 28, 2014
- 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