Ability for beforeSave() to convert INSERT into UPDATE.
In many to many relationship, there is often a need to just reuse an existing record on save.
In Yii 1.14 I can do something like this.
protected function beforeSave() {
$duplicate = $this->findByAttributes(array('symbol' => $this->stock_symbol));
if ($this->isNewRecord && $duplicate !== NULL) {
$this->id = $duplicate->id;
$this->isNewRecord = FALSE;
}
if ($this->isNewRecord === FALSE) {
return false;
}
return parent::beforeSave();
}
The problem is save() method will return false, making it look like save has failed.
The workaround is to also overload beforeValidate() but this method is not called when saving without validation.
protected function beforeValidate() {
if ($this->isNewRecord) {
$duplicate = $this->findByAttributes(array('symbol' => $this->stock_symbol)));
if (isset($duplicate)) {
$this->id = $duplicate->id;
$this->setIsNewRecord(false);
}
}
return parent::beforeValidate();
}