The easiest way is to take advantage of the afterSave() method in your model. This method will be called after each save process.
public function afterSave($insert, $changedAttributes) {
Another advantage of this method is the data that you saved in your object model. For example, to access the email field:
public function afterSave($insert, $changedAttributes) { //calling a send mail function \app\helpers\EmailHelper::send($this->email); return parent::afterSave($insert, $changedAttributes); }
the value of $this->email contains the save value in the database.
Note You can use $this->isNewRecord to determine if the model is saving a new record to the database or updating an existing record. Take a look:
public function afterSave($insert, $changedAttributes) { if($this->isNewRecord){
Now it sends mail only if the new record is stored in the database.
Please note that you can also use Yii2 EVENTS .
Like the official Yii2 documentation :
This method is called at the end of the insert or update record. The default implementation will raise the EVENT_AFTER_INSERT event when $ insert is true or the EVENT_AFTER_UPDATE event if $ insert is false. The event class used is yii\db\AfterSaveEvent . When overriding this method, be sure to call the parent implementation so that the event fires.
source share