在查看我的字段中
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
中使用我自己的书面方法。
您可以将
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
祝你好运,玩得开心!
规则:
['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;
}
玩转场景