nacesprin
nacesprin

Reputation: 482

Yii2: model rules inheritance on behavior

I dont know if there is another way to get this:

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']
];
    }
  ....
}

My question is: Is there any another way to inherit the rules from MyBehavior to UserModel with no use static calling MyBehavior::theRules() on UserModel::rules() ?

Upvotes: 1

Views: 3391

Answers (1)

nacesprin
nacesprin

Reputation: 482

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... 
                ]
            ;
}

Extracted from: 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]
        );
    }

Upvotes: 2

Related Questions