Incompatibility between find and saveAll in CakePHP
In a recent project I wanted to create a separate form for each record from a table using the form helper in CakePHP. After following the instructions found on the net I noticed that there was one big glaring problem.
The problem is that when loading the data the find(‘all’) model function would return data in the following format:
Array
(
[0] => Array
(
[ModelName] => Array
(
[id] => 83
[field1] => value1
[field2] => value2
[field3] => value3
)
)
)
However, the saveAll function accepts data in the following format:
Array
(
[Article] => Array(
[0] => Array
(
[title] => title 1
)
[1] => Array
(
[title] => title 2
)
)
)
The problem is that they’re reversed. One has the model name as the root key with an array of records inside and one has an array of model names with records.
There are a few ways to fix this, some even going so far as creating a new behavior or a new extended function of the model class.
Since this was a one-time use for me, I simply needed to switch the array around. The following code does just that:
$this->data = $this->Modelname->find('all');
$new_data = array();
foreach ($this->data as $row) {
array_push($new_data, $row['Modelname']);
}
$this->data = array('Modelname'=>$new_data);
I’m not to happy about making a round peg fit into a round hole when both were designed by the same folks, but this at least solves the problem.
Possibly related posts: