I have a model where I need to do some processing before savin开发者_运维知识库g (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
function beforeSave() {
if (!$this->id && !isset($this->data[$this->alias][$this->primaryKey])) {
// insert
} else {
// edit
}
return true;
}
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;
}
精彩评论