Sergey Onishchenko
Sergey Onishchenko

Reputation: 7851

Yii2 validation. Run filter on multiple attributes

public function rules()
{
    return [
        [['option_list', 'modifier'], 'filter', 'filter' => function($value) {
            // I can get the value but I don't know to which attribute it belongs (option_list or modifier)
        }],
    ];
}

How do I get an attribute name which is being processed? The only workaround that I found is to make separate filter for each attribute...

Upvotes: 0

Views: 338

Answers (1)

oakymax
oakymax

Reputation: 1474

The first parameter passed to validation function is $attribute so You can use it as follows

public function rules()
{
    return [
        [['option_list', 'modifier'], function($attribute) {
            // use $this->$attribute for conditions or filtering
            // use $this->addError($attribute, '<error message>') for adding errors
        }],
    ];
}

see http://www.yiiframework.com/doc-2.0/guide-input-validation.html#creating-validators

Upvotes: 1

Related Questions