Yii2: afterSave and isNewRecord in ActiveRecord

Created on 16 Jul 2014  路  1Comment  路  Source: yiisoft/yii2

For example, I create a new model and save it

$model = new Comment();
$model->scenario = 'guest';
$model->save();

In model i have afterSave callback:

    public function afterSave($insert, $changedAttributes)
    {
        if (($this->scenario == 'user' || $this->scenario == 'guest') && $this->isNewRecord)
            \Yii::$app->mailer->compose('new_comment', ['model' => $this])
                ->setFrom([\Yii::$app->params['supportEmail'] => \Yii::$app->name . ' robot'])
                ->setTo(Email::getByGroup(Email::COMMENTS))
                ->setSubject('Some subject')
                ->send();
        parent::afterSave($insert, $changedAttributes);
    }

Because, the isNewRecord property is overwritten I can't detect was the model saved right now or not.
Maybe it will be better don't overwrite isNewRecord property after first calling of the save() method?

Most helpful comment

Use $insert value.

>All comments

Use $insert value.

Was this page helpful?
0 / 5 - 0 ratings