yii2after-save

How to passing parameter to afterSave() Method in yii2?


I'm new to yii2. I want to write afterSave() method after insert new record. My scenario is: when the user add a damage must be send email to him. When user add damage, does not enter the serial number. I should read his name and serial damage but I don't know how to passing serial from Controller to model.

Damage Model:

public function getUser()
{
    return $this->hasOne(User::className(), ['id' => 'user_id']);
}

 public function afterSave($insert, $changedAttributes)
{
    parent::afterSave($insert, $changedAttributes);
    $name = $this->user->name;
    $serial = ?
    $to = $this->user->email;
    $subject = 'new damage';
    $body = 'mr'.$name.'your damage with serial number'.$serial.'is registered';
    if ($insert) {

        App::sendMail($to, $subject, $body);
    }
}

DamageController:

public function actionAddDamage($serial){

  $model = new Damage();
  $gaurantee = Gaurantee::find()->where(['serial' =>  $serial])->andWhere(['user_id' => Yii::$app->user->id])->one();
  if (!$gaurantee)
        throw  new ForbiddenHttpException('You don't access');
  $model->gr_id = $gaurantee->id;
  if ($model->load(Yii::$app->request->post()) && $model->save()) {

            return $this->redirect(['view', 'id' => $model->id]);
        }
  return $this->render('addDamage',
            ['model' => $model,
                'servers' => $servers,
                'gaurantee' => $gaurantee,
            ]);
}

Solution

  • First that comes to mind is to add attribute in damage model.

    //Damage model
    public $serial;
    

    Then in your controller you can set value for this:

    public function actionAddDamage($serial){
          $model = new Damage();
          $gaurantee = Gaurantee::find()->where(['serial' =>       $serial])->andWhere(['user_id' => Yii::$app->user->id])->one();
          if (!$gaurantee)
              throw  new ForbiddenHttpException("you don't access");
          $model->serial = $serial;
          .....
    

    In your afterSave() method you will have your serial as $this->serial.

    2nd way is to get it from guaranty table since you have $this->gr_id , but this will generate 1 more db request.