2

I have this weird error in my Yii2 Model's AfterSave Function

When I do this

public function afterSave($insert, $changedAttributes) {
    parent::afterSave($insert, $changedAttributes);
    if(!$insert):
        print_r($changedAttributes);exit;
        $this->prepareMail(self::MAIL_APPROVE);
    ;
}

I get

Array ( 
 [reason_for_travel] => 1 [project_id] => [billable] => 1  
 [advance_required] => 0 [status] => 2  ) // See it contains 'status'

But when i do this

public function afterSave($insert, $changedAttributes) {
    parent::afterSave($insert, $changedAttributes);
    if(!$insert):
        $status = $changedAttributes['status']; // this line shows error
        if($status == Self::STATUS_CONFIRMED):
           $this->prepareMail(self::MAIL_APPROVE);
        ;
    ;
}

$status = $changedAttributes['status']; This line shows error

Error is "Undefined index: status"

What am I not seeing ?

ck_arjun
  • 1,367
  • 1
  • 11
  • 19

2 Answers2

3

use this lines:

if(!$insert):
  $status = isset($changedAttributes['status']) ? $changedAttributes['status'] : 0); // this line shows error
    if($status == Self::STATUS_CONFIRMED):
       $this->prepareMail(self::MAIL_APPROVE);
    ;
;

$changedAttributes contains the old values of the modified fields but only modified fields, valid if exist with "isset" skip errors.

JCMD
  • 31
  • 2
0

How to check is an attribute has changed after saving

public function afterSave($insert, $changedAttributes){
    //isAttributeChangedAfterSave
    var_dump(array_key_exists('name', $changedAttributes) && $this->name != $changedAttributes['name']);

    //...
}

Note that isAttributeChanged() does not work in afterSave() because after saving, $this->oldAttributes is assigned new values.

Mike S
  • 192
  • 3
  • 9