CakePHP beforeSave() gotcha: need to set $this->__exists to true if setting a primary key

1 minute read Published:

I added an update to CakePHP Book: beforeSave()

Also, if you add a primary key which would turn an “insert” into an “update” within beforeSave() you’ll need to set $this->__exists = true;… the call to $this->exists(); happens in model.php before the callback to beforeSave().

function beforeSave() {
    if (!isset($this->data[$this->name]['id']) && isset($this->data[$this->name]['unique_field'])) {
        $found = $this->find("first",array(
                "recursive" => -1,
                "fields" => array("id"),
                "conditions" => array("unique_field" => $this->data[$this->name]['unique_field'])));
        if (!empty($found) && isset($found[$this->name]['id'])) {
            $this->id = $this->data[$this->name]['id'] = $found[$this->name]['id'];
            $this->__exists = true;
    return parent::beforeSave();

That’s been confusing me a bit recently – setting the ID of a row within beforesave() should change the save to an update, but it was trying to insert with a specified ID and thus, failing… glad to have a simple solution that makes sense… hope that helps someone else…

Published by in cakephp, development and php and tagged beforeSave, cake, cakephp and php using 134 words.

comments powered by Disqus