4

I need to have a generic JSON-representation of errors for any form that I have.

I have already read other solutions like in how to return json encoded form errors in symfony. But I don't want to create one more service for task that is already can be solved by other bundle that I connected to my project.

I use JMSSerializerBundle in my project and I know that this bundle can handle Symfony form errors using FormErrorHandler. But now I can get only whole form serialization:

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

This code will return me next JSON-object:

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

But I need something like that (only fields with errors):

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

How can I achieve that? I looked at FOSRestBundle that has already solved this problem. But I didn't find how they did it.

2
  • 1
    Have a look at this : JMSSerializer + forms/arrays. You might have to write your own handler to "flatten" the array : Subscribing Handlers Commented Jan 26, 2015 at 11:10
  • I know what I can. But I want to use solution that is already in JMSSerializerBundle (FormErrorHandler). How can I do this? Commented Jan 27, 2015 at 13:11

1 Answer 1

0

Using following code you can get errors the same structure you want:

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

Result

"{"children":{"title":{"errors":["This value should not be blank."]},"summary":{"errors":["Give your post a summary!"]},"content":{"errors":["Your post should have some content!"]}}}"
Sign up to request clarification or add additional context in comments.

1 Comment

This gives exactly the same output for me (jms/serializer 1.1.0 & SF 3.1.0)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.