0

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

Raheel
  • 8,716
  • 9
  • 60
  • 102

2 Answers2

1

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.

rob006
  • 21,383
  • 5
  • 53
  • 74
0

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

  • This answer in incorrect. `$this->$attribute` will evaluate for current context (for example if you do this in controller action, `$this` will point to controller), instead of actual model. – rob006 Nov 18 '19 at 14:25