我不知道是否还有另一种方法可以解决这个问题:
UserModel.php
public function behaviors()
{
//I use array_merge() because UserModel extends from another custom model.
return
array_merge(
parent::behaviors(),
[
MyBehavior::className(),
]
);
}
public function rules()
{
return
array_merge(
MyBehavior::theRules(),
[
list of UserModel rules...
]
);
MyBehavior.php
class MyBehavior extends Behavior
{
public static function theRules()
{
return [
[['attr'],'file']
];
}
....
}
我的问题是:有没有其他方法可以将规则从MyBehavior继承到UserModel而不使用静态调用UserModel :: rules()上的MyBehavior :: theRules()?
答案 0 :(得分:1)
UserModel.php
use yii\helpers\ArrayHelper;
public function behaviors()
{
//I use array_merge() because UserModel extends from another custom model.
return ArrayHelper::merge(
parent::behaviors(),
[
MyBehavior::className(),
]
);
}
public function rules()
{
return
[
list of UserModel rules...
]
;
}
摘自:https://github.com/yiisoft/yii2/issues/3772#issuecomment-45715176
MyBehavior.php
use \yii\validators\Validator;
public function attach($owner){
parent::attach($owner);
$owner->validators[] = Validator::createValidator('file', $this->owner, '_anexo'
,['skipOnEmpty' => true, 'extensions' => 'png, jpg, jpeg', 'maxFiles' => 5, 'maxSize'=>2000000]
);
}