19Oct/102
Returning your symfony form’s error schema as an array
While I wish there would exist a sfValidatorErrorSchema::toArray(), you can implement the following method on your BaseForm to easily retrieve your error schema as an array. This is especially handy when you want to return the errors in a JSON response.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php class BaseForm extends sfFormSymfony { public function getErrorSchemaAsArray() { $errorSchema = $this->getErrorSchema(); $array = array('global' => array(), 'named' => array()); foreach ($errorSchema->getGlobalErrors() as $error) { $array['global'][] = $error->getMessage(); } foreach ($errorSchema->getErrors() as $name => $error) { $array['named'][$name] = $error->getMessage(); } return $array; } } |
December 15th, 2010 - 19:13
Pratique!
Dommage que ca ne gère pas les erreurs d’embededForms.
December 16th, 2010 - 11:40
Et voilà une version un peu plus poussé que je vient de coder:
public static function transformErrorToSimpleArray($sfForm)
{
// Préparation des variables
$array = array();
$embeddedForms = array();
if ($sfForm instanceof sfFormObject)
{
// On stocke chacune des erreurs globales si il en existe
foreach ($sfForm->getErrorSchema()->getGlobalErrors() as $id => $error)
{
$array['_global'][] = $error->getMessage();
}
}
// Pour chaque element du formulaire
foreach ($sfForm as $id => $widget)
{
// si il y a plusieurs champs dans ce champ, on relance la
// procédure pour les parcourir un a un
if (count($sfForm[$id]) > 1)
{
// On récupère le tableau
$array_recursive = self::transformErrorToSimpleArray($sfForm[$id]);
// si il contient des erreurs
if (se::arrayContainsValue($array_recursive))
{
// On l’ajoute au autres
$array[$id] = $array_recursive;
}
}
else
{
// Si c’est un simple champs et qu’il y a une erreur
if (($error = $sfForm[$id]->getError()))
{
// On ajoute au tableau
$array[$id] = $error->getMessage();
}
}
}
return $array;
}