vignesh
vignesh

Reputation: 512

Cakephp: Adding multiple records to single Model with one comman field

I've wanted to add multiple records to a single model in cakephp. I've been followed his tutorial http://bit.ly/1jjR1U5 and it works like charm. But I need minor tweaking from his code. I need to make one field in the form as common for all the multiple records and save the model. I've explained below clearly his code and what I need.

Below is his code to add multiple records to single model. In add.ctp:

echo $this->Form->create('Model');
for($i = 0; $i < $count; $i++){
echo $this->Form->input("Model.$i.field1", array());
echo $this->Form->input("Model.$i.field2", array());
echo $this->Form->input("Model.$i.field3", array());
echo $this->Form->input("Model.$i.field4", array());
}
echo $this->Form->end('add');

In Controller, i.e ModelController.php inside add() action,

function add($count = 1){
if($this->request->is('post')){
    if($this->Model->saveAll($this->request->data['Model'])){
            $this->Session->setFlash(__('The Model has been saved'));
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The Model could not be saved. Please, try again.'));
        }
    $this->redirect(array('action' => 'index'));
}
    $this->set('count', $count);
}

The above code will create multiple inserts in the table. What I want is in the add.ctp form,

echo $this->Form->create('Model');
echo $this->Form->input("field1", array());
for($i = 0; $i < $count; $i++){     
 echo $this->Form->input("Model.$i.field2", array());
 echo $this->Form->input("Model.$i.field3", array());
 echo $this->Form->input("Model.$i.field4", array());
}
echo $this->Form->end('add');

Here I want the Field 1 to be common to the records to be inserted in the table. I don't want to loop it, because client have to select same option for field 1 in each iteration. If anybody knows how to achieve this using cakephp controller or form, please share your suggestions.

Upvotes: 0

Views: 3369

Answers (1)

Anil kumar
Anil kumar

Reputation: 4177

Try this

$this->request->data = Hash::insert($this->request->data, 'Model.{n}.field1', $this->request->data['Model']['field1']);
$this->request->data = Hash::remove($this->request->data, 'Model.field1');
if($this->Model->saveAll($this->request->data['Model'])) {
    // your stuff goes here
}

Upvotes: 3

Related Questions