除了Yii2中当前用户的用户名外,如何在表“用户"中唯一的字段“用户名"检查 [英] How to check my field `username` on unique in table `User` except current user's username in Yii2

查看:27
本文介绍了除了Yii2中当前用户的用户名外,如何在表“用户"中唯一的字段“用户名"检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在查看我的字段 username 总是由当前用户的用户名填充.它总是(在提交时)将用户名值发送到我的 InformationForm 并验证它的唯一性,如下所示:

[['username'], 'unique', 'targetAttribute' =>'用户名','目标类' =>'\common\models\User', 'message' =>'这个用户名不能被占用.'],

它说这个用户名已经被占用了.所以我想在那时检查我的值 username,它不是我的用户名.就像是我在数据库中的当前用户名 -> Bob我在字段 username 中查看的值 -> Bob我点击Submit,它不应该检查这个用户名是否是唯一的(显然是因为它是我的用户名)

就在那时,当我在数据库中的当前用户名 -> Bob和字段 username -> John 中的值然后我点击 Submit - 应该检查这个用户名是否唯一

我知道自定义验证器",因此我可以在我的 InformationForm 中使用我自己编写的方法来验证我的字段.我想找到如何完成我在这里写的所有内容,除了在我的 InformationForm 中使用我自己编写的方法.

解决方案

您可以将 when 属性用于 unique 验证器.

你在模型中的规则是:

<预><代码>[['用户名'], '唯一','目标属性' =>'用户名','目标类' =>'\common\models\User','消息' =>'这个用户名不能被占用.','当' =>功能($模型){return $model->username != Yii::$app->user->identity->getUsername();//或其他获取当前用户名的函数}],

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

祝你好运,玩得开心!

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.

解决方案

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!

这篇关于除了Yii2中当前用户的用户名外,如何在表“用户"中唯一的字段“用户名"检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆