Skip to content

Instantly share code, notes, and snippets.

@extolabs
Created May 12, 2011 16:19
Show Gist options
  • Save extolabs/968857 to your computer and use it in GitHub Desktop.
Save extolabs/968857 to your computer and use it in GitHub Desktop.
Form Errors Symfony
private function getAllFormErrors($children, $template = true) {
foreach ($children as $child) {
if ($child->hasErrors()) {
$vars = $child->createView()->getVars();
$errors = $child->getErrors();
foreach ($errors as $error) {
$this->allErrors[$vars["name"]][] = $this->convertFormErrorObjToString($error);
}
}
if ($child->hasChildren()) {
$this->getAllErrors($child);
}
}
}
public function getAllErrors($children, $template = true) {
$this->getAllFormErrors($children);
return $this->allErrors;
}
private function convertFormErrorObjToString($error) {
$errorMessageTemplate = $error->getMessageTemplate();
foreach ($error->getMessageParameters() as $key => $value) {
$errorMessageTemplate = str_replace($key, $value, $errorMessageTemplate);
}
return $errorMessageTemplate;
}
@ihortymoshenko
Copy link

$errors = array();
foreach ($form->getChildren() as $child) {
    if ($child->hasErrors()) {
        foreach ($child->getErrors() as $error) {
            $errors[$child->getName()][] = $error->getMessageTemplate();
        }
    }
}

@yapro
Copy link

yapro commented Nov 26, 2013

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);

@jjmonagas
Copy link

Thanks @yapro It works!

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