AleŇ° AleŇ° -4 years ago 567
PHP Question

Yii2 before save check if attributes are changed

I want to check if some attributes in my model are changed in

beforeSave()
method according to data sotred in database.

Is there some best practice how to check if model is changed?

My goal si to make history. If some attribute changes, I save a copy into
model_history
table

Answer Source

You can actually do that using afterSave().

public function afterSave($insert, $changedAttributes) {
    parent::afterSave($insert, $changedAttributes);
    if(!$insert) {
        // your code here like $changedAttributes['myField'];
    }
}

$changedAttributes saves the values of the attributes that were changed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download