It's not clear to me how I should use the Symfony Form Component with FOSRestBundle for POST endpoints that I use to create resources.
Here is what I've got in my POST controller action:
//GuestController.php
public function cpostAction(Request $request)
{
$data = json_decode($request->getContent(), true);
$entity = new Guest();
$form = $this->createForm(GuestType::class, $entity);
$form->submit($data);
if ($form->isValid()) {
$dm = $this->getDoctrine()->getManager();
$dm->persist($entity);
$dm->flush();
return new Response('', Response::HTTP_CREATED);
}
return $form;
}
What I do is:
- Send an
application/json
POST request to the endpoint (/guests
); - Create a form instance that binds to an entity (
Guest
); - Due to the fact that I'm sending JSON, I need to
json_decode
the request body before submitting it to the form ($form->submit($data)
).
The questions I have:
- Do I really always have to
json_decode()
theRequest
content manually before submitting it to a Form? Can this process be somehow automated with FosRestBundle? - Is it possible to send
application/x-www-form-urlencoded
data to the controller action and have it handled with:
-
$form->handleRequest($request)
if ($form->isValid()) {
...
}
...
I couldn't get the above to work, the form instance was never submitted.
- Is there any advantage of using the Form Component over using a
ParamConverter
together with the validator directly - here is the idea:
-
/**
* @ParamConverter("guest", converter="fos_rest.request_body")
*/
public function cpostAction(Guest $guest)
{
$violations = $this->getValidator()->validate($guest);
if ($violations->count()) {
return $this->view($violations, Codes::HTTP_BAD_REQUEST);
}
$this->persistAndFlush($guest);
return ....;
}
Thanks!