Feed on
Posts
Comments

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…

One Response to “Cakephp Beforesave() Gotcha: Need To Set $this->__exists To True If Setting A Primary Key”

  1. Brad Koch says:

    You’re missing lots of ].

Leave a Reply

Bad Behavior has blocked 225 access attempts in the last 7 days.