Unable to access attributes values in Dynamic Model validation Yii2

291 Views Asked by At

I am trying to validate user input.

$params = Yii::$app->getRequest()->getBodyParams();
$model = new DynamicModel($params);
$model->addRule(['userId', 'category', 'type'], 'required');
$model->addRule('userId', 'integer');
$model->addRule('category',
    function ($attribute, $params, $validator) use ($model) {
        var_dump($params); exit;
    });
$model->validate();
return $model;

How can I access the value of category parameter so that I can apply my validation logic. Currently its getting null

2

There are 2 best solutions below

0
rob006 On BEST ANSWER

You need something like this:

$model->addRule(
    'category',
    function ($attribute, $params, $validator) use ($model) {
        if (empty($model->$attribute)) {
            $model->addError($attribute, 'Error message');
        }
    }
);

Inline validators are explained in the guide.

1
Shringiraj Dewangan On

Correct these line below mentioned

$model->addRule('category',
    function ($attribute, $params, $validator) { //<---remove use($model)
        var_dump($this->$attribute); exit;  //<--- correct this line
        /*make logic here*/

    }
);

the closer function define here but it will call form inside of model so that, $this->$attribute variable is working