私はyii2が初めてです。afterSave()
新しいレコードを挿入した後にメソッドを書きたい。私のシナリオは次のとおりです。ユーザーが損害を追加した場合、ユーザーに電子メールを送信する必要があります。ユーザーがダメージを追加するとき、シリアル番号を入力しません。彼の名前とシリアルの損傷を読む必要がありますが、コントローラーからモデルにシリアルを渡す方法がわかりません。
ダメージモデル:
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);
}
}
ダメージコントローラー:
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,
]);
}