How to get parameters from a PUT request in Symfony2?

I am using Symfony 2.3, and I have a method that looks like this:

public function addAction() { $user = new User(); $form = $this->createForm(new UserType(), $user); $form->handleRequest($this->getRequest()); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($user); $em->flush(); try { return $this ->render( 'SomeBundle:Default:adduser.html.twig', array('id' => $user->getId())); } catch (Exception $e) { throw new HttpException(500, "Error persisting"); } } throw new HttpException(400, "Invalid request"); } 

using this route:

 some_bundle_adduserpage: pattern: /user defaults: { _controller: SomeBundle:User:add } methods: [POST] 

and everything works fine. I also have this method:

 public function editAction($id) { $response = new Response(); if (!$this->doesUserExist($id)) { $response->setStatusCode(400); return $response; } $user = new User(); $form = $this->createForm(new UserType(), $user); $form->handleRequest($this->getRequest()); if (!$form->isValid()) { $response->setStatusCode(400); return $response; } $user->setId($id); $em = $this->getDoctrine()->getManager(); try { $em->persist($user); $em->flush(); $response->setStatusCode(200); } catch (Exception $e) { $response->setStatusCode(500); } return $response; } 

using this route:

 some_bundle_edituserpage: pattern: /user/{id} defaults: { _controller: SomeBundle:User:edit } methods: [PUT] requirements: id: \d+ 

and it does not work. I can handle some request, and POST is just fine, but PUT not working. In particular, it looks like I'm not getting any parameters inside $this->getRequest() . Why $this->getRequest() work for POST but not PUT ? What am I doing wrong?

+6
source share
2 answers

This did the trick:

$form = $this ->createForm(new UserType(), $user, array('method' => 'PUT'));

The method bit was missing. Symfony doesn't seem to be cool enough to just get the options for you. When creating a form, you need to manually specify which requests it is associated with. Although this worked, I am not sure if this is the best answer. I am more than willing to hear others.

+1
source

The PUT method is passed directly to stdin , so you must use php://input and fopen with read to access it.

 $put = fopen("php://input", "r"); 

Disclaimer for Symfony may be a built-in method, but I forgot.

0
source

All Articles