Note that there are some explanatory texts on larger screens.

plurals
  1. POCakePHP - changing from insert to update in Model->beforeSave()
    text
    copied!<p>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.</p> <pre><code> public function beforeSave(){ if ($this-&gt;checkExisting() !== false){ $this-&gt;id = $this-&gt;checkExisting(); } return true; } </code></pre> <p>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.</p> <p>What this code actually does is insert a new record, regardless.</p> <p>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.</p> <p>At what stage does Cake decide to do an insert, rather than an update? Is beforeSave() too late to affect this decision?</p> <p>Edit - here's my controller code:</p> <pre><code>public function add(){ if (!empty($this-&gt;data)){ $saved = 0; foreach($this-&gt;data['Attendance'] as $att){ $this-&gt;Attendance-&gt;create(); if ($this-&gt;Attendance-&gt;save(array('Attendance'=&gt;$att))){ $saved++; } if ($saved &gt; 0){ $this-&gt;Session-&gt;setFlash('Data saved successfully','success'); }else{ $this-&gt;Session-&gt;setFlash('No data was saved. Please make sure you have entered some data.','failure'); } } } } </code></pre> <p>Thinking about it, is it something to do with the fact that I explicitly call Attendance::create()?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload