How can I tell if I'm in beforeSave from an ed

2020-07-05 03:29发布

问题:

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

回答1:

function beforeSave() {
  if (!$this->id && !isset($this->data[$this->alias][$this->primaryKey])) {
    // insert
  } else {
    // edit
  }
  return true;
}


回答2:

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;
}