-1

I am creating a web application that stores user's journeys and I'm build this application in CakePHP 2.2.5.

I have a Journey model and that journey model has many coordinate objects which store the lat long coordinates.

I'd like to send an API call to the journey's add method containing json in the body to create a new object.

I've tried to find out how to format the JSON to allow the controller to use it but I cant seem to find out. I'd also like to know how to add the child objects to the JSON.

I am testing the method using this cURL command

curl -i -H "ACCEPT: application/json" -X POST --data @/home/sam/data.json http://localhost/journeys/add.json

Running this CURL command create a blank entry in the database.

The JSON file included in the CURL contains

{"description" : "Hello World", "user_id":3}
Sam Marland
  • 552
  • 3
  • 24

2 Answers2

1

It's better to convert json to array(with json_decode function) then manipulate your array, If you want at last convert it to json(json_encode function).

cakePHP handle this task by : JsHelper::object

edit 1: but I think when php do it for you , it's better use php pure function instead of cakePHP functions.

edit 2: I think cakePHP doesn't handle it , you should handle it by yourself, convert your json to array, change your array as you want in foreach then pass it to saveAll function to insert or update in database.

Arash Mousavi
  • 2,110
  • 4
  • 25
  • 47
  • Does CakePHP not automatically handle the JSON? – Sam Marland Jan 11 '13 at 18:16
  • Thanks for your edit. Maybe I wasn't clear in my initial post but what I'm looking for is the syntax to build the JSON myself so that when I call `$this->Journey->save($this->request->data` in my controller it should know where each element of the JSON should go. Similar to what is is in this link [CakePHP Docs](http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savemany-array-data-null-array-options-array) – Sam Marland Jan 11 '13 at 18:31
0

I've done some more research and found a solution to my problem:

CakePHP will save JSON data and it will also save nested model information.

$data = $this->request->input('json_decode');

Which is similar to what @Arash said but it will also save nested model information by calling

$this->Journey->saveAssociated($data)

The JSON I'm providing to the controller looks like:

{"Journey":
{"description":"Not even an article from the map", "user_id":3}, 
"Coordinate":[
    {"lat":54.229149, "lng":-5.114115},
    {"lat":54.39153, "lng":-5.114113}
 ]
}

Where coordinate belongs to Journey.

Sam Marland
  • 552
  • 3
  • 24