how to return json encoded form errors in symfony how to return json encoded form errors in symfony symfony symfony

how to return json encoded form errors in symfony


I am using this, it works quiet well:

/** * List all errors of a given bound form. * * @param Form $form * * @return array */protected function getFormErrors(Form $form){    $errors = array();    // Global    foreach ($form->getErrors() as $error) {        $errors[$form->getName()][] = $error->getMessage();    }    // Fields    foreach ($form as $child /** @var Form $child */) {        if (!$child->isValid()) {            foreach ($child->getErrors() as $error) {                $errors[$child->getName()][] = $error->getMessage();            }        }    }    return $errors;}


I've finally found the solution to this problem here, it only needed a small fix to comply to latest symfony changes and it worked like a charm:

The fix consists in replacing line 33

if (count($child->getIterator()) > 0) {

with

if (count($child->getIterator()) > 0 && ($child instanceof \Symfony\Component\Form\Form)) {

because, with the introduction in symfony of Form\Button, a type mismatch will occur in serialize function which is expecting always an instance of Form\Form.

You can register it as a service:

services:form_serializer:    class:        Wooshii\SiteBundle\FormErrorsSerializer

and then use it as the author suggest:

$errors = $this->get('form_serializer')->serializeFormErrors($form, true, true);


This does the trick for me

 $errors = []; foreach ($form->getErrors(true, true) as $formError) {    $errors[] = $formError->getMessage(); }