Wonderful methods beforeSave () and afterSave () in Yii2 help us to solve various problems, for example, you want before saving the database to change the date format, or save the log action. But not everyone knows how to inherit them.

Let's start with a simple afterSave():

public function afterSave($insert, $changedAttributes){
parent::afterSave($insert, $changedAttributes);
//... to do
}

There is nothing complicated, we simply pass to the parent method all the same settings and run it, and then do everything we needed.

Now beforeSave():

public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
//... to do
return true;
}
return false;
}

All the practical as well as with afterSave() method, except that we need to return the result of the parent method, otherwise we when calling $model->save() will get false, and our model will not be saved, nor do we we will receive no errors. Remember this moment.

Yii1 The principle is the same, only the parameters are not transferred there.