Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Insert multiple Form Data in CakePHP as new row in database

Tags:

php

mysql

cakephp

I use Jquery Clone for adding more form for filling data. then i want to add all data of form individually in a new row of database. database table will be.ex. according 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
                )

        )

)
like image 928
Manish Prajapati Avatar asked Jan 17 '26 02:01

Manish Prajapati


2 Answers

you will have to put your data in saveAll compatible format like this

array(
'Book' => array(
 0 => array(
  'name' => 'xxx',
  'author' => 'yyy',
 ),
 1 => array(
  'name' => 'aaa',
  'author' => 'bbb',
 )
)
)

you can do that by traforming your jquery clone passed data. something like this. 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];
   }

then simply call saveAll in your Book model

$this->saveAll($data);

assuming your data arrived in the format you provided above

like image 136
Cholthi Paul Ttiopic Avatar answered Jan 19 '26 17:01

Cholthi Paul Ttiopic


Generate the 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 the data like -

array(
  'Book' => array(
     0 => array(
      'name' => 'xxx',
      'author' => 'yyy',
     ),
     1 => array(
      'name' => 'aaa',
      'author' => 'bbb',
     )
  )
)

Then the saveMany() will work with them properly.

like image 27
Sougata Bose Avatar answered Jan 19 '26 17:01

Sougata Bose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!