0
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...

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, it is, but for validators. Notice, that I use "filter".
@SergeyOnishchenko yes, but actually filter is just one of Yii2 core validators. in own rule you can easily perform filtering too.
Yes this is ok, but in this case it's not so obvious that data modification is taking place instead of validation.
@SergeyOnishchenko it's just the semantic value of validation rule name. You can name your validation rule function myFilter and use it as filter. Or You can create own validation class with proper call semantic (maybe inherited from built-in Filter)

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.