0

yii2 how to make a notification by e-mail to the user after changing his status?? Help me, Please!

Model

class Applicants extends \yii\db\ActiveRecord
{
    public $file;
    public static function tableName()
    {
        return 'applicants';
    }

    public function rules()
    {
        return [
            [['user_id', 'type_passport_id', 'passport_number', 'date', 'expiration_date', 'passport_path', 'diplom_number', 'diplom_path', 'phone_number', 'mobile_number', 'country_id', 'city_id', 'address', 'faculty_id', 'spec_id', 'stage_id', 'training_id', 'dormitories_id'], 'required'],
            [['user_id', 'type_passport_id', 'country_id', 'city_id', 'status_id', 'faculty_id', 'spec_id', 'stage_id', 'training_id', 'dormitories_id'], 'integer'],
            [['passport_number', 'mobile_number', 'applicants_comment'], 'string', 'max' => 250],
            [['expiration_date'], 'string', 'max' => 120],
            [['file'], 'file', 'skipOnEmpty' => true, 'extensions' => 'pdf'],
            [['passport_path', 'diplom_path', 'address'], 'string', 'max' => 255],
            [['diplom_number'], 'string', 'max' => 50],
            [['phone_number'], 'string', 'max' => 30],
            [['user_id'], 'unique'],
            [['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
        ];
    }

Help me, Please!

2 Answers2

1

You can use afterSave($insert,$changedAttributes) to check for changed attributes and send the email.

According to the DOCS $changedAttributes parameter has old values of attributes that had changed and were saved. You can use this parameter to take action based on the changes made for example send an email when the password had changed or implement audit trail that tracks all the changes. $changedAttributes gives you the old attribute values while the active record ($this) has already the new, updated values.

public function afterSave( $insert , $changedAttributes ) {

    if ( !$insert && isset ( $changedAttributes['status'] ) ) {
        $this->sendEmail ();
    }
    return parent::afterSave ( $insert , $changedAttributes );
}

private function sendEmail() {
    //your code to email
}
Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68
-1
public function afterSave($insert, $changedAttributes){
    if (!$insert && array_key_exists('status_id', $changedAttributes) && $this->status_id != $changedAttributes['status_id']){
        $this->sendEmail();
    }
    return parent::afterSave($insert, $changedAttributes);
}

private function sendEmail() {
    //your code to email
}

The best way to check is an attribute has changed afterSave(). See Note in this answer

Mike S
  • 192
  • 3
  • 9