Link
Link

Reputation: 699

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.

Upvotes: 2

Views: 2920

Answers (2)

falko
falko

Reputation: 1457

Rule:

['email', 'unique', 'targetClass' => self::class, 'when' => [$this, 'whenSelfUnique']

When handler method:

public function whenSelfUnique($model, $attribute) {
    /**
     * @var ActiveRecord $model
     */
    $condition = $model->getOldPrimaryKey(true);
    return !self::find()->where(array_merge($condition, [$attribute => $model->$attribute]))->exists();
}

or

public function whenSelfUnique($model, $attribute) {
    if (!\Yii::$app->user->isGuest) {
        return \Yii::$app->user->identity->$attribute !== $model->$attribute;
    }
    return true;
}

Play with scenarios

Upvotes: 0

ThanhPV
ThanhPV

Reputation: 463

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!

Upvotes: 5

Related Questions