Question on the yii2 framework.

How to find out in afterSave, has the field value changed?

I work with notifications to issue a message when a particular field has changed.

Here I use this scheme, when insert all the rules, I find out the necessary data

public function afterSave($insert, $changedAttributes) { if ($insert) { // Да это новая запись (insert) } else { // Нет, старая (update) } parent::afterSave($insert, $changedAttributes); } 

But what about update? I, for example, have a status - 0/1 field status - 0/1 . If the value has changed, I need to find out the id of the record, and write it to another table. How to do this, can someone dock?

    1 answer 1

    getOldAttribute () - returns the previous value

    getOldAttributes () - returns all attributes and their values ​​before changes

     if ($insert) { // Да это новая запись (insert) } else { if($this->status != $this->getOldAttribute('status')){ //...$this->id } } 

    There is also an isAttributeChanged () method, its principle is the same as described above.

     if ($insert) { // Да это новая запись (insert) } else { if($this->isAttributeChanged('status')){ //...$this->id } } 
    • print_r($this->status); and print_r($this->getOldAttribute('status')); They give the same values - Vlad Shkuta
    • Judging by the commit - github.com/yiisoft/yii2/commit/ ... , it should work correctly, maybe where is the error elsewhere, what does beforeSave on the same expression? - Bookin
    • Yes, strange. in beforeSave works correctly. - Vlad Shkuta
    • In principle, it will work in beforeSave , id does not change, but in essence only id is needed. Thank you - Vlad Shkuta