Brett
Brett

Reputation: 20049

Using filters from other classes within rules method in Yii 2?

Consider this code inside a model:

public function rules() {
    return [
        [['company_name', 'first_name', 'last_name'], 'sanitize'],
        //........
    ];
}

sanitize is a custom method inside the current class, which is:

public function sanitize($attribute) {
    $this->{$attribute} = general::stripTagsConvert($this->{$attribute}, null, true);
}

Now this method obviously will come in handy in many models so I don't want to keep repeating the same code in every model. Is there a way I can reference another class in the rules in place of the current sanitize method name which is binded to the current class?

Upvotes: 0

Views: 1247

Answers (1)

arogachev
arogachev

Reputation: 33538

Yes, it's definitely possible.

Create separate validator. Let assume it's called SanitizeValidator and placed in common/components folder.

Your custom validator must extend from framework base validator and override validateAttribute() method. Put your logic inside this method:

use yii\validators\Validator;

class SanitizeValidator extends Validator
{
    /**
     * @inheritdoc
     */
    public function validateAttribute($model, $attribute)
    {
        $model->$attribute = general::stripTagsConvert($model->$attribute, null, true);
    }
}

Then in model you can attach this validator like this:

use common/components/SanitizeValidator;

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [['company_name', 'first_name', 'last_name'], SanitizeValidator::className()],
    ];
}

Check the official documentation about custom validators here and there.

Upvotes: 1

Related Questions