Skip to content

Instantly share code, notes, and snippets.

@svparijs
Forked from dework/FormErrors.php
Created October 9, 2017 09:04
Show Gist options
  • Save svparijs/1d18ea6e3f8144e88e77701d819c09c8 to your computer and use it in GitHub Desktop.
Save svparijs/1d18ea6e3f8144e88e77701d819c09c8 to your computer and use it in GitHub Desktop.
Symfony 2 Get All Form Errors
<?php
namespace Chyrius\SiteBundle\Form;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Form\Form;
/**
* @todo Обрабатывать так же ошибки детей-детей
*/
class FormErrors
{
private $container;
/**
* @param \Symfony\Component\Form\Form $form
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
* @param \Symfony\Component\Form\Form $form
* @return array
*/
public function getFormErrors(Form $form)
{
//
if ($err = $this->childErrors($form)) {
$errors["form"] = $err;
}
//
foreach ($form->all() as $key => $child) {
//
if ($err = $this->childErrors($child)) {
$errors[$key] = $err;
}
}
return $errors;
}
/**
* @param \Symfony\Component\Form\Form $form
* @return array
*/
public function childErrors(Form $form)
{
$errors = array();
foreach ($form->getErrors() as $error) {
// Переведем ошибку, если есть перевод
$message = $this->container->get('translator')->trans($error->getMessage(), array(), 'validators');
array_push($errors, $message);
}
return $errors;
}
}
services:
chyrius.form_errors:
class: Chyrius\SiteBundle\Form\FormErrors
arguments: [ @service_container ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment