Here's my beforeSave function. checkExisting() checks whether some of the fields in $this->data are unique, and returns false if there is no existing record, or the ID of the existing record, if it exists. This function is working fine.
public function beforeSave(){
if ($this->checkExisting() !== false){
$this->id = $this->checkExisting();
}
return true;
}
What I think my code should do is this: if there is an existing record, set the Model->id to the ID of that existing record, and so force CakePHP to update instead of insert.
What this code actually 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), as Cake is still trying to insert, rather than update, data.
At what stage does Cake decide to do an insert, rather than an update? Is beforeSave() too late to affect this decision?
Edit - here's 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 it, is it something to do with the fact that I explicitly call Attendance::create()?