Skip to content

[DX] Add a JsonSerializable implementation to FormErrorIterator and FormError. #11309

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
goabonga opened this issue Jul 5, 2014 · 3 comments
Closed
Labels
DX DX = Developer eXperience (anything that improves the experience of using Symfony) Form

Comments

@goabonga
Copy link
Contributor

goabonga commented Jul 5, 2014

Every time when i need to return form errors to json I need to transform manually errors in my controller like:

/** @var array $errors */
$errors = array();
/** @var FormError $error */
foreach($form->getErrors(true) as $error)
{
    $errors[] = array('message'=>$error->getMessage());
}
$response = new JsonResponse();
$response->setData(array(
    'errors' => $errors
));

but with this simple implementation we can do:

/** @var JsonResponse $response */
$response = new JsonResponse();
$response->setData(array(
    'form'=>array(
            'errors' => $form->getErrors(true)
    )
));

I do not see if this implementation can have any adverse side effect.

@Nek-
Copy link
Contributor

Nek- commented Jul 5, 2014

👍

@webmozart
Copy link
Contributor

Hi @goabonga, thank you for proposing this feature! I think this is a good idea. However, we can only add this with Symfony 3.0 as before that we need to support PHP 5.3.

We should find out what information of a FormError is typically needed when returning errors from an API. Things that come to mind:

  • the error message
  • the code of the underlying exception/constraint violation? (via getCause())
  • maybe the field/property path that the error occurred on?

I'm not sure about all of this. Any input @lsmith77?

@goabonga
Copy link
Contributor Author

Hi @webmozart,

It's can be "formidable" if next version respect the jsonapi specification.
(the specification introduce error objects. http://jsonapi.org/format/#error-objects ).

What do you think about it ?

github format :

 {
   "message": "Validation Failed",
   "errors": [
     {
       "resource": "Issue",
       "field": "title",
       "code": "missing_field"
     }
   ]
 }

https://developer.github.com/v3/#client-errors

fabpot added a commit that referenced this issue Mar 23, 2018
… (lyrixx)

This PR was merged into the 4.1-dev branch.

Discussion
----------

[Serializer] Added a ConstraintViolationListNormalizer

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | #11309
| License       | MIT
| Doc PR        | -

---

It seems logical to me that Symfony is able to serialise natively some very common Symfony data structure. (and requested by @nicolas-grekas & @javiereguiluz )

Usage example (from symfony/symfony-demo):

```php
    /**
     * @route("", name="api_blog_new")
     * @method("POST")
     * @Security("is_granted('ROLE_ADMIN')")
     */
    public function newAction(Request $request)
    {
        $data = $request->getContent();

        $post = $this->get('serializer')->deserialize($data, Post::class, 'json', ['groups' => ['post_write']]);

        $post->setAuthor($this->getUser());

        $violations = $this->get('validator')->validate($post);

        $post->setSlug($this->get('slugger')->slugify($post->getTitle()));

        if (count($violations) > 0) {
            $repr = $this->get('serializer')->serialize($violations, 'json');

            return JsonResponse::fromJsonString($repr, 400);
        }

        $this->getDoctrine()->getManager()->persist($post);
        $this->getDoctrine()->getManager()->flush();

        $repr = $this->get('serializer')->serialize($post, 'json', ['groups' => ['post_read']]);

        return JsonResponse::fromJsonString($repr);
    }
```

Commits
-------

2a35d09 [Serializer] Added a ConstraintViolationListNormalizer
@fabpot fabpot closed this as completed Mar 23, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
DX DX = Developer eXperience (anything that improves the experience of using Symfony) Form
Projects
None yet
Development

No branches or pull requests

5 participants