ActiveRecord.php
public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            if (isset(\Yii::$app->user)) {
                $user_id = \Yii::$app->user->id;

                if ($this->isNewRecord) {
                    if ($this->hasAttribute('created_by'))
                        $this->created_by = $user_id;
                } else {
                    if ($this->hasAttribute('updated_by'))
                        $this->updated_by = $user_id;
                }
            }
            return true;
        }
        return false;
    }
public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            if (isset(\Yii::$app->user)) {
                $user_id = \Yii::$app->user->id;

                if ($this->isNewRecord) {
                    if ($this->hasAttribute('created_by'))
                        $this->created_by = $user_id;
                } else {
                    if ($this->hasAttribute('updated_by'))
                        $this->updated_by = $user_id;
                }
            }
            return true;
        }
        return false;
    }
Actions to be taken before saving the record.
@param bool $insert
@return bool whether the record can be saved