首页 > 解决方案 > 在行为 yii2 的 init 中获取模型的属性

问题描述

这是我的代码:

class CalculatedFieldsBehavior extends Behavior {
    public $calcFields = array();

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

    public function init() {
        foreach ($this->owner->attributes() as $attribute) {
            if (strpos($attribute, 'calc_')) {
                if (!is_function(get_parent_class()::$set . \yii\helpers\camelize($attribute))) {
                    throw Exception("Function to set value of calc field '" . $attribute . "' not defined.");
                }

                $calcFields[] = $attribute;
            }
        }

        if (!($this->owner->hasAttribute('isCalcValueSet'))) {
            throw Exception("This table is missing a field for isCalcValueSet");
        }

        parent::init();
    }
}

并给出这个错误:

"name": "Exception",
"message": "Call to a member function attributes() on null",
"code": 0,
"type": "Error",
"file": "D:\\xampp\\htdocs\\backoffice\\common\\models\\CalculatedFieldsBehavior.php",
"line": 25,

标签: yii2yii2-advanced-app

解决方案


$owner中不可用init()。它设置在attach(). 通常工作流程如下所示:

$behavior = new MyBehavior(); // init() is called here
$behavior->attach($owner); // owner is set here

您可能应该attach()在您的情况下覆盖:

public function attach($owner) {
    foreach ($owner->attributes() as $attribute) {
        if (strpos($attribute, 'calc_')) {
            if (!is_function(get_parent_class()::$set . \yii\helpers\camelize($attribute))) {
                throw Exception("Function to set value of calc field '" . $attribute . "' not defined.");
            }

            $calcFields[] = $attribute;
        }
    }

    if (!($owner->hasAttribute('isCalcValueSet'))) {
        throw Exception("This table is missing a field for isCalcValueSet");
    }

    parent::attach($owner);
}

推荐阅读