5

I am using dynamic model in my yii2 basic application.

following is code of 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 willing to user custom validation function 'checkRm' form from_rm field i have also defined checkRm function like this :

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

But when i submit form i get error Class checkRm does not found

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

I have also tried when and whenClient conditions but those are also not working

2 Answers 2

1

Try this:

$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:

Yes, it works. But if you want to test with an empty value for from_rm, you need to set skipOnEmpty to false. Example:

    $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());
Sign up to request clarification or add additional context in comments.

1 Comment

Hi mat0ng thanks for your answer.. but it is also not working for me.. have you tried it?
0

This works if checkRm is a method of DynamicModel class. So either extend DynamicModel and add this method or use closure like:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.