Here is my beforeSave function. checkExisting () checks if some of the fields in $ this-> data are unique, and returns false if there is no existing record or identifier of an existing record if it exists. This function works fine.
public function beforeSave(){ if ($this->checkExisting() !== false){ $this->id = $this->checkExisting(); } return true; }
I think my code should do this: if there is an existing entry, set the Model-> ID to this existing entry and thus force update CakePHP instead of pasting.
What this code really does is insert a new record, regardless.
If I change $ this-> id = $ this-> checkExisting (); to $ this-> data ['Model'] ['id'] = $ this-> checkExisting () ;, MySQL gives an error (duplicate value for the primary key), because Cake is still trying to insert, not update, the data.
At what stage does Cake decide to insert, not update? Is beforeSave () too late to affect this decision?
Edit - here is my controller code:
public function add(){ if (!empty($this->data)){ $saved = 0; foreach($this->data['Attendance'] as $att){ $this->Attendance->create(); if ($this->Attendance->save(array('Attendance'=>$att))){ $saved++; } if ($saved > 0){ $this->Session->setFlash('Data saved successfully','success'); }else{ $this->Session->setFlash('No data was saved. Please make sure you have entered some data.','failure'); } } } }
Thinking about this, is it because I explicitly call Attendance :: create ()?
source share