Skip to content

Instantly share code, notes, and snippets.

@dework
Last active October 9, 2017 09:04
Show Gist options
  • Select an option

  • Save dework/4968094 to your computer and use it in GitHub Desktop.

Select an option

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 ]
@yapro

yapro commented Nov 26, 2013

Copy link
Copy Markdown

Get Translated Form Error Messages (Symfony2.3)

My version of solving the problem:
/src/Intranet/OrgunitBundle/Resources/config/services.yml

services:
    form_errors:
        class: Intranet\OrgunitBundle\Form\FormErrors

/src/Intranet/OrgunitBundle/Form/FormErrors.php

<?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;
    }
}

/src/Intranet/OrgunitBundle/Controller/DefaultController.php

$form = $this->createFormBuilder($entity)->getForm();
$form_errors = $this->get('form_errors')->getArray($form);
return new JsonResponse($form_errors);

@midnai

midnai commented Oct 17, 2014

Copy link
Copy Markdown

Thank You!

@inri13666

Copy link
Copy Markdown

Я бы немного ещё добавил

   foreach ($form->all() as $key => $child) {
        if($child instanceof \Symfony\Component\Form\Form){
            if ($err = $this->childErrors($child)) {
                $errors[$key] = $err;
            }
        }
    }

Т.к. иногда SubmitButton тоже уже есть в форме

Что в принципе решено во 2 варианте ))

@antongorodezkiy

Copy link
Copy Markdown

Спасибо!

@jeff1985

Copy link
Copy Markdown

Korpch's function seems to be broken. Did not work as expected for me.

yapro's version worked, but was missing translation. Also it generated an array of arrays, which is not what i expected to get. I was looking for a way to get a simple plain list of error messages to display them to the user.

My final version:

     /**
     * @param \Symfony\Component\Form\Form $form
     * @return string[]
     */
    public static function getFormErrors(\Symfony\Component\Form\Form $form)
    {
        $errors = array();

        if ($form instanceof \Symfony\Component\Form\Form) {
            // find errors of this element
            foreach ($form->getErrors() as $error) {
                $errors[] = self::$translator->trans($error->getMessage(), array(), 'validators');
            }

            // iterate over errors of all children
            foreach ($form->all() as $key => $child) {
                if($child instanceof \Symfony\Component\Form\Form) {
                    /** @var $child \Symfony\Component\Form\Form */
                    $err = self::getFormErrors($child);
                    if (count($err) > 0) {
                        $errors = array_merge($errors, $err);
                    }
                }
            }
        }

        return $errors;
    }

@max107

max107 commented Nov 9, 2016

Copy link
Copy Markdown

@yapro о привет

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