user2511599
user2511599

Reputation: 852

Yii2 unique validator as adhoc validator

How can I convert this:

public function rules() {
    return [
        [['attr1', 'attr2'], 'unique', 'skipOnEmpty' => false, 'skipOnError' => false, targetAttribute' => ['attr1', 'attr2']],

into an inline validator, or what would be the equivalent of this as an inline validator? Thank you.

Upvotes: 0

Views: 83

Answers (1)

Is not possible to use Unique validator as ad hoc as explained in https://www.yiiframework.com/doc/guide/2.0/en/input-validation#ad-hoc-validation:

Note: Not all validators support this type of validation. An example is the unique core validator which is designed to work with a model only.

You will have to build it by yourself.

Other way could be to wrap the query into a try catch, assuming that you have a unique key on the db. The db will complain about the query and you can catch the error.


Edit for inline validation:

This is a very specific validator, something you will not reuse so, lets write it inline as an anonymous function:

public function rules(){
    [['attr1'], function(){
        //we know the names of the attribute so we use them here directly instead of pass as a parameter
        if(self::find()->where([
            'attr1' => $this->attr1, 
            'attr2' => $this->attr2
        ])->exists()){
            $this->addError('attr1', 'Error message');
            $this->addError('attr2', 'Error message');
        }
    }]
}

Notice I just registered validation for attr1. If you register also attr2, you will end with 2 errors per each attribute.

Upvotes: 1

Related Questions