Saturday, May 26, 2012

Re: Using PUT request method does not populate data with values

Hi,

I was stuck a few days ago in exactly the same situation. Curl sends the post data correctly (You can see it doing a curl trace) but cake doesn't populate the $this->data. I found out that PHP doesn't have a built in support for PUT as it does with POST and GET ($_POST, $_GET) so to get the data you need to do processing in the input. This is what I do in my edit actions:

if ($this->request->is('post'))
{
$data=$this->request->data;
}
if ($this->request->is('put'))
{
parse_str(file_get_contents("php://input"),$data);
}

This works but I'm not entirely sure is the best way to populate the data array.

Have fun,
David


On Friday, May 25, 2012 12:49:05 PM UTC+2, elitalon wrote:
Hi,

I am developing an API using CakePHP 2.1.1. I have configured the following route:

Router::connect("/api/accounts/:id",
  array('controller' => 'accounts', 'action' => 'edit', 'api' => true, '[method]' => array('PUT', 'POST')),
  array('pass' => array('id'), 'id' => '\d+'));

Then I have the following action:

public function api_edit($id = null) {
  if ($this->request->is('put') || $this->request->is('post')) {
    if ($this->Account->save($this->request->data)) {
      ...
    } else {
      throw new InternalErrorException();
    }
  } else {
    throw new MethodNotAllowedException();
  }
}

I am testing the API using curl. When using POST the action saves the data and everything goes as expected:

$ curl -i -X POST -d "data[Account][id]=1&data[Account][name]=FooBar" http://example.com/api/accounts/1.json
HTTP/1.1 200 OK

However, when using PUT $this->request->data is not populated with the submitted data but returns an empty array():

$ curl -i -X PUT -d "data[Account][id]=1&data[Account][name]=FooBar" http://example.com/api/accounts/1.json
HTTP/1.1 500 Internal Server Error

Both requests are entering the action and passing the check of $this->request->is(...). But printing the content of $this->request->data before saving just reveals this scenario.

Any ideas? If not I'll submit this issue as a ticket.

Thanks!!

--
Our newest site for the community: CakePHP Video Tutorials http://tv.cakephp.org
Check out the new CakePHP Questions site http://ask.cakephp.org and help others with their CakePHP related questions.
 
 
To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php

No comments: