如何检查我的字段“username”在表“User”中是否唯一,除了 Yii2 中当前用户的用户名

问题描述 投票:0回答:2

在查看我的字段中

username
始终由当前用户的用户名填充。它总是(在提交时)将用户名值发送到我的
InformationForm
并对其进行唯一验证,如下所示:

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

它说该用户名已被占用。所以我想检查一下我的值

username
,这不是我的用户名。就像是 我当前在数据库中的用户名 -> Bob 我在现场的价值
username
-> 鲍勃 我点击
Submit
并且它不应该检查该用户名是否唯一(显然因为这是我的用户名)

就在那时,当我当前的用户名在数据库中 -> Bob 以及字段中视图的值

username
-> John 我点击
Submit
- 应该检查该用户名是否唯一

我了解“自定义验证器”,因此我可以使用我自己的书面方法来验证我的字段

InformationForm
。我想找到如何完成我在这里写的所有内容,除了在我的
InformationForm
中使用我自己的书面方法。

php validation yii2
2个回答
5
投票

您可以将

when
属性用于
unique
验证器。

模型中的规则是:

[
    ['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
    }
],

可以参考yii2文档:http://www.yiiframework.com/doc-2.0/yii-validators-validator.html#$when-detail

祝你好运,玩得开心!


0
投票

规则:

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

当处理程序方法:

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

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

玩转场景

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.