Skip to content

Instantly share code, notes, and snippets.

@midnai
Last active August 29, 2015 14:07
Show Gist options
  • Save midnai/29b3979bf3d16583325b to your computer and use it in GitHub Desktop.
Save midnai/29b3979bf3d16583325b to your computer and use it in GitHub Desktop.
Symfony 2.3 Get All Form Errors
<?php
By yapro
File Service: /src/Intranet/OrgunitBundle/Resources/config/services.yml
services:
form_errors:
class: Intranet\OrgunitBundle\Form\FormErrors
File Class: /src/Intranet/OrgunitBundle/Form/FormErrors.php
namespace Intranet\OrgunitBundle\Form;
class FormErrors
{
public function getArray(\Symfony\Component\Form\Form $form)
{
return $this->getErrors($form);
}
private function getErrors($form)
{
$errors = array();
if ($form instanceof \Symfony\Component\Form\Form) {
foreach ($form->getErrors() as $error) {
$errors[] = $error->getMessage();
}
foreach ($form->all() as $key => $child) {
/** @var $child \Symfony\Component\Form\Form */
if ($err = $this->getErrors($child)) {
$errors[$key] = $err;
}
}
}
return $errors;
}
}
File Controller: /src/Intranet/OrgunitBundle/Controller/DefaultController.php
$form = $this->createFormBuilder($entity)->getForm();
$form_errors = $this->get('form_errors')->getArray($form);
return new JsonResponse($form_errors);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment