Skip to content

Instantly share code, notes, and snippets.

@dework
Last active October 9, 2017 09:04
Show Gist options
  • Save dework/4968094 to your computer and use it in GitHub Desktop.
Save dework/4968094 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 ]
@max107
Copy link

max107 commented Nov 9, 2016

@yapro о привет

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment