M
M
Messi2017-10-20 10:11:33
Yii
Messi, 2017-10-20 10:11:33

How to make behavior for afterSave event?

Can you please tell me how to create behavior for models?
There are two models: User and Staff (Active Record entities) , they have common actions on afterSave($insert, $changedAttributes).
I want to put it in behavior.
Created a class myBehavior extends AttributeBehavior
in events subscribed to event after insert
Moved here public function afterSave($insert, $changedAttributes) , and in models in behavior just connected myBehavior::className()
When I save the user, afterSave fires, but insert and changeAttributes do not transferred. Why and how to do it right?

<?php

namespace frontend\components;

use common\models\Log;
use yii\behaviors\AttributeBehavior;
use yii\db\ActiveRecord;

class EntityLogBehavior extends AttributeBehavior
{

    public function events()
    {
        return [
            ActiveRecord::EVENT_AFTER_INSERT => 'afterSave',
        ];
    }


    /**
     * @param bool $insert
     * @param array $changedAttributes
     */
    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        // some logic
        Log::add(Yii::$app->user->identity->id, $this::className(), $this->id, $action);
    }
}



// А это в модели User
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            EntityLogBehavior::className()
        ];
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2017-10-20
@FitTech

Excuse me for being rude, but you wrote nonsense that cannot work, firstly, when the behavior on events is triggered, the specified function is passed not the attributes you set, but an instance of the yii\base\Event class i.e. no $insert and $changedAttributes will be passed, in your case an instance of the yii\db\AfterSaveEvent class will be passed to the method . Second, why are you inheriting from AttributeBehavior? according to the code, there is no sense from this inheritance, except for the afterSave method that you call in the code
in the AttributeBehavior class. And the correct way to implement your behavior is something like this:

class EntityLogBehavior extends \yii\base\Behavior
{
    public function events()
    {
        return [
            ActiveRecord::EVENT_AFTER_INSERT => 'afterSave',
        ];
    }

    public function afterSave($event)
    {
        $event->changedAttributes // читаем и что-то делаем с измененными атрибутами
    }
}

PS I strongly recommend that you study in detail the very concept of behaviors

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question