How to get form errors in Symfony as a JSON object with JMSSerializer

I need to have a common JSON representation of errors for any form I have.

I already read other solutions, such as how to return json encoded form errors in symfony . But I do not want to create another service for a task that can already be solved by another package that I connected to my project.

I use JMSSerializerBundlein my project, and I know that this package can handle Symfony form errors using FormErrorHandler. But now I can only get serialization of the whole form:

$errors = $form->getErrors();
$serializer = $this->get('jms_serializer');
$json = $serializer->serialize($errors, 'json');

This code will return the following JSON object to me:

{
    "form": {
        "children": {
            "field1": [],
            "field2": [],
            "field_with_error": {
                "errors": ["Error text"]
            },
            "collection": {
                "child_form": [
                    {
                        "children": {
                            "field1": [],
                            "field2": []
                        }
                    }
                ]
            }
        }
    },
    "errors": []
}

But I need something like this (only error fields):

{
    "field_with_error": {
        "errors": ["Error text"]
    }
}

? FOSRestBundle, . , .

+4
1

, , :

$handler = new FormErrorHandler($this->get('translator'));
$visitor = new JsonSerializationVisitor(new SerializedNameAnnotationStrategy(new CamelCaseNamingStrategy()));
$errors = json_encode($handler->serializeFormToJson($visitor, $editForm, array()));

"{"children":{"title":{"errors":["This value should not be blank."]},"summary":{"errors":["Give your post a summary!"]},"content":{"errors":["Your post should have some content!"]}}}"
0

All Articles