yii2 - 在行为 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,
解决方案
$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);
}
推荐阅读
- kotlin - Kotlin Jetpack 从 Button 组合声音?
- javascript - 如何获取 alert.prompt 输入并使用它来操作数据?
- logistic-regression - 使用 GradientTape 的多类逻辑回归
- gradle - 原始错误: ANDROID_HOME 和 ANDROID_SDK_ROOT 环境变量均未导出。在 Mac 上为 Appium
- terraform - Terraform - 为 CloudFront IP 自动创建 SG
- javascript - 这里公共交通路线到车站的最大距离不起作用
- javascript - 为什么 React-grid-layout 的位置没有改变?
- lua - 为什么我的 logitech g lua 脚本出现语法错误?
- css - 如何在 VScode 中编写 CSS 注释 emmet?
- react-native - ReactNativeJS: TypeError: undefined is not an object (评估 'u.Children.toArray(n.children).filter(function(n){return null!=n})[t].props')