Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if I'm in beforeSave from an edit or a create? CakePHP

I have a model where I need to do some processing before saving (or in certain cases with an edit) but not usually when simply editing. In fact, if I do the processing on most edits, the resulting field will be wrong. Right now, I am working in the beforeSave callback of the model. How can I tell if I came from the edit or add?

Frank Luke

like image 735
Frank Luke Avatar asked Nov 17 '09 20:11

Frank Luke


2 Answers

function beforeSave() {
  if (!$this->id && !isset($this->data[$this->alias][$this->primaryKey])) {
    // insert
  } else {
    // edit
  }
  return true;
}
like image 156
neilcrookes Avatar answered Oct 25 '22 06:10

neilcrookes


This is basically the same as neilcrookes' answer, except I'm using empty() as the test, as opposed to !isset().

If an array key exists, but is empty, then !isset will return false, whereas empty will return true.

I like to use the same view file for add and edit, to keep my code DRY, meaning that when adding a record, the 'id' key will still be set, but will hold nothing. Cake handles this fine, except neilcrookes version of the code won't recognise it as an add, since the primaryKey key is set in the data array (even though it holds nothing). So, changing !isset to empty just accounts for that case.

function beforeSave() {
  if (!$this->id && empty($this->data[$this->alias][$this->primaryKey])) {
    // insert
  } else {
    // edit
  }
  return true;
}
like image 30
joshua.paling Avatar answered Oct 25 '22 07:10

joshua.paling