Last active
August 29, 2015 14:07
-
-
Save midnai/29b3979bf3d16583325b to your computer and use it in GitHub Desktop.
Symfony 2.3 Get All Form Errors
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 | |
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