How to add custom validation function to dynamic model in Yii2?

I am using a dynamic model in my base yii2 application.

Below is the code for my dynamic model.

$model = new \yii\base\DynamicModel([
        'role', 'from_rm', 'to_rm', 'user1_subdistrcts'
    ]);
    $model->addRule(['user1_subdistrcts', 'role'], 'required', ['message' => "Please select this field."])
->addRule(['from_rm'], 'checkRm');

here I am ready for the custom validation function 'checkRm' form from_rmfield I also defined the function checkRm as follows:

public function checkRm($from_rm, $params)
{
    $this->addError($from_rm, 'Please Select Regional Manager.');
}

But when I submit the form, I get an error. Class CheckRm not found.

Now please help how to use custom validation in a dynamic model.

I also tried the conditions whenand whenClient, but they also do not work

+4
source share
2 answers

Try the following:

$model = new \yii\base\DynamicModel([
    'role', 'from_rm', 'to_rm', 'user1_subdistrcts'
]);
$model->addRule('from_rm', function ($attribute, $params) use ($model) {
    $model->addError($attribute, 'Please Select Regional Manager.');
});

EDIT:

, . from_rm, skipOnEmpty false. :

    $model = new \yii\base\DynamicModel([
        'role', 'from_rm', 'to_rm', 'user1_subdistrcts'
    ]);
    $model->addRule('from_rm', function ($attribute, $params) use ($model) {
        $model->addError($attribute, 'Please Select Regional Manager.');
    }, [
        'skipOnEmpty' => false,
    ]);

    $model->validate();
    var_dump($model->getErrors());
+1

, checkRm - DynamicModel. DynamicModel , , :

...->addRule(['from_rm'], function ($attribute, $params) {
    $this->addError($from_rm, 'Please Select Regional Manager.');
});
0

Source: https://habr.com/ru/post/1658537/


All Articles