jabey
jabey

Reputation: 17

aftersave() and beforesave() with dirty attributes

I'm new Yii2. I'm stuck in a point of triggering changed attributes in update. I just need to get changed attributes and save another table record is changed to new value.

Please any one could help me to solve this with before save, after save and dirty attributes?

Upvotes: 0

Views: 2849

Answers (2)

Chendong
Chendong

Reputation: 11

In ActiveRecord model:

public function afterSave($insert, $changeAttributes)
{
    parent::afterSave($insert, $changeAttributes);

    // $changeAttributes
}

Upvotes: 0

Kalu
Kalu

Reputation: 571

Use the getAttributes() and getOldAttributes methods in yii\db\ActiveRecord. ie:

public actionUpdate($id)
{
    $model = $this->findModel($id);
    if ($model->load(Yii::$app->request->post())) {
        $changed_attributes = array_diff_assoc($model->getOldAttributes(), $model->getAttributes());
        if($model->save()) {
            //Save changed values in other table
           //$changed_attributes contains attribute_name=>value pairs of changed(old) attributes. and $model contains new values. 
        }
    }
}

Upvotes: 2

Related Questions