FOSRestBundle posting json data to a form not working
Since nobody replied, I am going to answer myself in this question.
First of all, sent JSON must start with form name, so instead:
{"firstName": "John", "lastName": "Doe", "emailAddress": "something@somewhere.com", "sex": "1"
must be:
{"user": {"firstName": "John", "lastName": "Doe", "emailAddress": "something@somewhere.com", "sex": "1"}}
In my case, form name was "user".
I have used CURL to test it:
curl -v -H "Accept: application/json" -H "Content-type: application/json" -XPOST -d "{\"user\":{\"firstName\":\"John\", \"emailAddress\": \"somewhere@somehow.com\", \"password\":\"verystrongmuchpower\"}}" http://localhost.software.com/app_dev.php/api/1.0/users
Since I am testing the API with CURL, a difference in response in bind and handleRequest is gone.
I will update this answer soon if I get more conclusions.
i solved it like this:
$user = new User; $form = $this->createForm(UserType::class, $user); $view = View::create(); $form->submit($request->request->all()); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($user); $em->flush(); $view->setData($form->getData()); } else { $view->setData($form); } return $this->handleView($view);
Don't forget to disable CSRF validation (https://symfony.com/doc/master/bundles/FOSRestBundle/2-the-view-layer.html#csrf-validation)
fos_rest: disable_csrf_role: ROLE_API #disable_csrf_role: IS_AUTHENTICATED_ANONYMOUSLY #just for testing
Then you get a nice output like this:
{"code": 400,"message": "Validation Failed","errors": { "children": { "name": { "errors": [ "This value should not be blank." ] }, "role": { "errors": [ "This value should not be blank." ] } } }}