28

I want to create a webservice to which I submit a form, and in case of errors, returns a JSON encoded list that tells me which field is wrong.

currently I only get a list of error messages but not an html id or a name of the fields with errors

here's my current code

public function saveAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();

    $form = $this->createForm(new TaskType(), new Task());

    $form->handleRequest($request);

    $task = $form->getData();

    if ($form->isValid()) {

        $em->persist($task);
        $em->flush();

        $array = array( 'status' => 201, 'msg' => 'Task Created'); 

    } else {

        $errors = $form->getErrors(true, true);

        $errorCollection = array();
        foreach($errors as $error){
               $errorCollection[] = $error->getMessage();
        }

        $array = array( 'status' => 400, 'errorMsg' => 'Bad Request', 'errorReport' => $errorCollection); // data to return via JSON
    }

    $response = new Response( json_encode( $array ) );
    $response->headers->set( 'Content-Type', 'application/json' );

    return $response;
}

this will give me a response like

{
"status":400,
"errorMsg":"Bad Request",
"errorReport":{
        "Task cannot be blank",
        "Task date needs to be within the month"
    }
}

but what I really want is something like

{
"status":400,
"errorMsg":"Bad Request",
"errorReport":{
        "taskfield" : "Task cannot be blank",
        "taskdatefield" : "Task date needs to be within the month"
    }
}

How can I achieve that?

dbc
  • 104,963
  • 20
  • 228
  • 340
SimonQuest
  • 662
  • 1
  • 5
  • 17

6 Answers6

32

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;
}
COil
  • 7,201
  • 2
  • 50
  • 98
  • Unfortunately this didn't work for me, at least not the way I wanted. Thanks you very much for answering – SimonQuest Jul 08 '14 at 09:08
  • 1
    it doesn't traverse properly the form structure if it's not a simple one and it's not returning the input fields ids/names. Maybe My explanation of the problem wasn't clear enough. Try the solution I've found, you'll understand. – SimonQuest Jul 08 '14 at 09:18
  • Yes indeed, it's for one level forms only. – COil Jul 19 '14 at 19:30
17

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);
SimonQuest
  • 662
  • 1
  • 5
  • 17
8

This does the trick for me

 $errors = [];
 foreach ($form->getErrors(true, true) as $formError) {
    $errors[] = $formError->getMessage();
 }
iamtankist
  • 3,464
  • 1
  • 19
  • 25
1

PHP has associative arrays, meanwhile JS has 2 different data structures : object and arrays.

The JSON you want to obtain is not legal and should be :

{
"status":400,
"errorMsg":"Bad Request",
"errorReport": {
        "taskfield" : "Task cannot be blank",
        "taskdatefield" : "Task date needs to be within the month"
    }
}

So you may want to do something like this to build your collection :

$errorCollection = array();
foreach($errors as $error){
     $errorCollection[$error->getId()] = $error->getMessage();
}

(assuming the getId() method exist on $error objects)

Delapouite
  • 9,469
  • 5
  • 36
  • 41
  • 1
    for id or name of the field I mean something that I can use to target the field in form... like an html id or name of the field. – SimonQuest Jul 03 '14 at 14:37
  • If your iterate with foreach($errors as $key => $error), isn't $key what you're looking for? – Delapouite Jul 03 '14 at 14:43
  • no, it would simply be a numerical index... I need something to target the html element – SimonQuest Jul 03 '14 at 14:46
  • @SimonQuest This [answer](http://stackoverflow.com/questions/6978723/symfony2-how-to-get-form-validation-errors-after-binding-the-request-to-the-fo#answer-8216192) (and subsequent) may help you. – rolebi Jul 06 '14 at 22:17
0

By reading other people's answers I ended up improving it to my needs. I use it in Symfony 3.4.

To be used in a controller like this:

$formErrors = FormUtils::getErrorMessages($form);

return new JsonResponse([
    'formErrors' => $formErrors,
]);

With this code in a separate Utils class

<?php

namespace MyBundle\Utils;

use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormInterface;

class FormUtils
{
    /**
     * @param FormInterface $form
     * @return array
     */
    public static function getErrorMessages(FormInterface $form)
    {
        $formName = $form->getName();
        $errors = [];

        /** @var FormError $formError */
        foreach ($form->getErrors(true, true) as $formError) {
            $name = '';
            $thisField = $formError->getOrigin()->getName();
            $origin = $formError->getOrigin();
            while ($origin = $origin->getParent()) {
                if ($formName !== $origin->getName()) {
                    $name = $origin->getName() . '_' . $name;
                }
            }
            $fieldName = $formName . '_' . $name . $thisField;
            /**
             * One field can have multiple errors
             */
            if (!in_array($fieldName, $errors)) {
                $errors[$fieldName] = [];
            }
            $errors[$fieldName][] = $formError->getMessage();
        }

        return $errors;
    }
}
Julesezaar
  • 2,658
  • 1
  • 21
  • 21
0

This will do the trick. This static method runs recursively through the Symfony\Component\Form\FormErrorIterator delivered by calling $form->getErrors(true, false).

<?php


namespace App\Utils;


use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormErrorIterator;

class FormUtils
{
    public static function generateErrorsArrayFromForm(FormInterface $form)
    {
        $result = [];
        foreach ($form->getErrors(true, false) as $formError) {
            if ($formError instanceof FormError) {
                $result[$formError->getOrigin()->getName()] = $formError->getMessage();
            } elseif ($formError instanceof FormErrorIterator) {
                $result[$formError->getForm()->getName()] = self::generateErrorsArrayFromForm($formError->getForm());
            }
        }
        return $result;
    }
}

Here is the result :

{
    "houseworkSection": "All the data of the housework section must be set since the section has been requested.",
    "foodSection": {
        "requested": {
            "requested": "This value is not valid."
        }
    }
}