How to insert multiple form data in CakePHP as a new line in the database
I am using JQuery Clone to add an additional form to fill in the data. then I want to add all the form data separately to a new database row. the database table will be. over my array.
name | author | category
ABC 2 1
XYZ 2 1
PQR 5 2
my array
Array
(
[Book] => Array
(
[name] => Array
(
[0] => ABC
[1] => XYZ
[2] => PQR
)
[author] => Array
(
[0] => 2
[1] => 2
[2] => 5
)
[category] => Array
(
[0] => 1
[1] => 1
[2] => 2
)
)
)
+3
source to share
3 answers
you will need to put your data in a saveAll compatible format like
array(
'Book' => array(
0 => array(
'name' => 'xxx',
'author' => 'yyy',
),
1 => array(
'name' => 'aaa',
'author' => 'bbb',
)
)
)
you can do this by going through jquery cache data transfer. something like that. Note: not tested
$data = array();
$names = Hash::extract($jquerycloneData,'Book.name');//array(ABC,XYZ,PQR);
$authors = Hash::extract($jquerycloneData,'Book.author');
$categories = Hash::extract($jquerycloneData,'Book.category');
$i=0;
for($i, $i<count($names) ,$i++){
$data['Book'][$i]['name'] = $names[$i];
$data['Book'][$i]['author'] = $authors[$i];
$data['Book'][$i]['category'] = $categories[$i];
}
and then just call saveAll on your workbook.
$this->saveAll($data);
Assuming your data is received in the format you specified above
+3
source to share
Create form fields with names like -
echo $this->Form->input('Book.0.name');
echo $this->Form->input('Book.1.name');
echo $this->Form->input('Book.0.author');
echo $this->Form->input('Book.1.author');
Then you will get data like -
array(
'Book' => array(
0 => array(
'name' => 'xxx',
'author' => 'yyy',
),
1 => array(
'name' => 'aaa',
'author' => 'bbb',
)
)
)
Then it saveMany()
will work with them properly.
+3
source to share