tags:

views:

1091

answers:

1

Hi,

I'm trying to duplicate a particular entry in the form. I get all the column values by their form id, and trying to save it as a new row using saveAll. But instead of creating a new row, it is updating the existing entry.

Here is my code:

function duplicateForm($data)
   {
         $this->data['Form']['id']=$data['Form']['id'];
         $existingForm=$this->find('all',array('conditions'=>array('Form.id'=>$this->data['Form']['id'])));

         foreach($existingForm as $ex):
             $this->data['Form']['name']=$ex['Form']['name']." (copy)";
              $this->data['Form']['created_by']=$ex['Form']['created_by'];
               $this->data['Form']['access']=$ex['Form']['access'];
                 $this->data['Form']['status']='Incompleted';
                if($this->saveAll($this->data)) 
                {echo "Success";}
         endforeach;
   }

I thought maybe since the Form name is same, it is getting updated. So I added the 'copy' string to the name of the form. Yet the old entry is only getting updated.

These are the columns of my table 'Form' and their type:

    Field            Type   

  id              int(11)    
  name              varchar(25)  
  created_by      int(11)    
  access          varchar(10)  
  created          timestamp    
  modified          timestamp     
  status          varchar(15)

The id field is auto-increment,so I thought that If I give a save method, the id will be generated of its own.

+2  A: 

Cake decides whether to update an existing record or save data as a new one by the presence of the id field and the existence of this id in the database. Since you include the id, it'll always update the existing record.

You could greatly simplify your code like this:

$form = $this->read(null, $data['Form']['id']);

unset($form['Form']['id']);  // no id == new record
$form['Form']['status'] = 'Incompleted';

$this->create();
$this->save($form);

As general advice: Don't copy contents of arrays one by one into another array, especially if it's your model data. First of all it's tedious, but more importantly, if you ever add a new column to your Form table, you'll either have to hunt down all the places where that new field should be copied as well, or, more likely, you'll introduce funny bugs because that new field is missing whenever you duplicate a Form.

deceze
Yeah,it works.. Thanks for your help and advice.. I'll avoid copying contents of arrays one by one and go by this method..
Angeline Aarthi
But will this method work, if I have many records with the same id(not the primary id)?? If there are many records, I must go for using a for each loop right?
Angeline Aarthi
Sure, if you're using something other than the primary id you may get many records. Take care to call `$this->create()` in that case or use `saveAll()`. http://book.cakephp.org/view/75/Saving-Your-Data
deceze