It is not clear to me how I should use the Symfony form component with FOSRestBundle for the POST endpoints that I use to create resources.
Here is what I 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 am I doing:
- Send the
application/json POST request to the endpoint ( /guests ); - Create an instance of the form that is associated with the entity (
Guest ); - Due to the fact that I'm sending JSON, I need the
json_decode body of the request before sending it to the form ( $form->submit($data) ).
Questions I have:
- Should I always have
json_decode() contents of the Request manually before submitting it to the form? Can this process be automated in some way using the FosRestBundle? - Is it possible to send
application/x-www-form-urlencoded data to a controller action and process it with:
-
$form->handleRequest($request) if ($form->isValid()) { ... } ...
I could not get the above to work, an instance of the form was never submitted.
- Is there any advantage to using the form component using
ParamConverter together with the validator directly - here is the idea:
-
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!
source share