Search code examples
phpvalidationyii2

How to check my field `username` on unique in table `User` except current user's username in Yii2


In view my field username always filled by current user's username. And it always (on submit) sends username value to my InformationForm and validate it on unique like next:

[['username'], 'unique', 'targetAttribute' => 'username', 'targetClass' => '\common\models\User', 'message' => 'This username can not be taken.'],

And it say's that this username has already been taken. So i want to check my value username just then, whet it's not my username. It's like My current username in database -> Bob My value in view in field username -> Bob I click Submit and it should't check if this username is unique (obviously because it's my username)

And just then, when my current username in database -> Bob And value in view in field username -> John And i click Submit - is should check if this username is unique

I know about "custom validator" so i can validate my field using my own written method in my InformationForm. And i want to find how to do all i wrote here except using my own written method in my InformationForm.


Solution

  • You can use when property for unique validator.

    And your rules in models is:

    [
        ['username'], 'unique', 
        'targetAttribute' => 'username', 
        'targetClass' => '\common\models\User', 
        'message' => 'This username can not be taken.',
        'when' => function ($model) {
            return $model->username != Yii::$app->user->identity->getUsername(); // or other function for get current username
        }
    ],
    

    You can refer to yii2 document: http://www.yiiframework.com/doc-2.0/yii-validators-validator.html#$when-detail

    Goodluck and have fun!