2016-07-07 27 views
1

在我看來我的字段username總是由當前用戶的用戶名填充。它總是(上提交)發送的用戶名值到我的InformationForm和驗證它像一個唯一:如何檢查我的字段`用戶名`唯一的表`用戶`除當前用戶的用戶名在Yii2

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

它說的是這個用戶名已被佔用。所以我想檢查我的價值username就在那時,這不是我的用戶名。這就像 我在數據庫中當前用戶名 - >鮑勃 我鑑於字段值username - >鮑勃 我點擊Submit它should't檢查,如果這個用戶名是唯一的(很明顯,因爲這是我的用戶名)

而就然後,當我目前的用戶名在數據庫 - >鮑勃 和價值鑑於場username - >約翰 而且我點擊Submit - 是應該檢查一下這個用戶名是唯一

我知道的「自定義驗證」這樣我就可以在我的InformationForm中使用我自己的書面方法驗證我的領域。我想找到如何做我寫在這裏,除了在我的InformationForm使用我自己的書面方法。

+0

您是否創建了用於獲取此輸入的模型InformationForm?因爲你不必這樣做。這可能就是你爲什麼用獨特的驗證器來面對這個問題的原因。 – Clyff

+0

@Clyff,我創建模型InformationForm驗證我的領域,並把它們(如果它們是新的)到數據庫。 – Link

回答

2

您可以使用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

我有下一個 '[[ '用戶名'], '獨特', 'targetAttribute'=> '用戶名', 'targetClass'=> '\共同\模型\用戶', '時'=> \t \t \t \t函數($模型,$屬性) \t \t \t \t { \t \t \t \t \t $是否新款= FALSE; \t \t \t \t if($ model - > $ attribute!= User :: find() - > $屬性){ \t \t \t \t \t \t $ isNew = true; \t \t \t \t \t} \t \t \t \t \t回$是否新款; >「此用戶名不能採取 \t \t \t \t}, \t \t \t \t '消息'。'],' 而我有這樣的錯誤 'call_user_func()期望參數1是一個有效的回調函數'uniqueExceptItSelf'未找到或無效的函數名稱' – Link

+0

我使用你的代碼,它的工作! 我的Yii2版本是2.0.9 – ThanhPV

相關問題