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

半腔热情 提交于 2019-12-11 05:16:49

问题


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.


回答1:


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!




回答2:


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



来源:https://stackoverflow.com/questions/38253470/how-to-check-my-field-username-on-unique-in-table-user-except-current-users

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!