【发布时间】:2016-11-16 08:06:23
【问题描述】:
我正在编写一个小部件,我想避免用户向他们的模型添加代码(我知道这会更容易,但用它来学习新东西)。
您知道是否可以将属性(不在您的数据库中,因此它将是虚拟的)添加到模型并为该属性添加规则?您无权更改该型号代码。
我知道规则是一个数组。过去,我使用 array_merge 合并了父类的规则。可以在外部完成吗? Yii2 有方法吗?
一个想法是在我的小部件内使用“模型”扩展用户提供的模型并在那里使用:
public function init() {
/*Since it is extended this not even would be necessary,
I could declare the attribute as usual*/
$attribute = "categories";
$this->{$attribute} = null; //To create attribute on the fly
parent::init();
}
public function rules() {
$rules = [...];
//Then here merge parent rules with mine.
return array_merge(parent::rules, $rules);
}
但是如果我扩展它,当我在 ActiveForm 中使用该模型作为复选框时,它将使用我的“CustomModel”,所以我想避免这种情况。还有其他想法吗?如何在不扩展他们的模型的情况下做到这一点?
【问题讨论】: