Yii2: UnknownMethodException DynamicModel - each custom validator

Created on 20 May 2020  路  8Comments  路  Source: yiisoft/yii2

After update the Yii2 version to 2.0.35 from 2.0.34 the _each_ validator doesn't work with _custom validation function._ I suspect #18012 to have cause this problem (or #17944?).

What steps will reproduce the problem?

Set up custom validation function with each within a model class:

public $staff_ids;

public function rules()
{
    return [
        ...
        ['staff_ids', 'each', 'rule' => ['string']],
        [['staff_ids'], 'each', 'rule' => ['validateStaffIds']],
        ...
    ];
}

public function validateStaffIds($attribute, $params, $validator)
{
   ...
}

What is the expected result?

For each id within the staff_ids the custom validater validateStaffIds is called.

What do you get instead?

Error:
yii\base\UnknownMethodException: Calling unknown method: yii\base\DynamicModel::validateStaffIds() in /srv/http/ig-net/vendor/yiisoft/yii2/base/Component.php:300

Additional info

| Q | A
| ---------------- | ---
| Yii version | 2.0.35
| PHP version | v7.4.5
| Operating system | Manjaro 5.4.39
| Webserver | Nginx 1.18

bug

All 8 comments

@ricardomm85, @bizley would you please take a look?

That should be #17944 when the model was replaced with dynamic model.

I think I have a solution. Let me test it a bit before PR.

Looks like it works, let me know what you think.

@1Luc1 please check if it is OK with master version.

With v2.0.34 i used the attribute within the costume validator as follow (continuing the example from above):

public function validateStaffIds($attribute, $params, $validator)
{
   ...
   if (is_numeric($this->$attribute)) {
      ...
   }
}

Where this custom validator function is called for each element within _staff_ids_.

With v2.0.36-dev it doesn't work like that anymore and i have to change it as follow to at least don't get any errors:

public function validateStaffIds($attribute, $params, $validator)
{
   ...
   if (is_numeric($this->$attribute[0])) {
      ...
   }
}

As i can see from debug logs, _validateStaffIds_ is only called once and $this->$attribute has the same values as _staff_ids_.

I don't know if this is indented to work like that? If so, i have to run through all values with a loop within the custom validator function.

Indeed one more thing was missing for this to work like before the change (fingers crossed).

Unfortunately it's more complicated now that I thought. Please check the PR above for more info.

Was this page helpful?
0 / 5 - 0 ratings