從資料庫唯一驗證中驗證唯一值
如果正在輸入現有值,則有些人會出現有關錯誤訊息未顯示的問題。例如,我不允許使用者註冊現有的電子郵件。
檢視
<?php
......................
<?= $form->field($modelUser, 'email')->textInput(['class'=>'form-control','placeholder'=>'Email']) ?>
......................
調節器
<?php
use yii\web\Response; // important lines
use yii\widgets\ActiveForm; // important lines
.
.// Your code
.
public function actionSignup()
{
$modelUser = new User();
//Add This For Ajax Validation
if(Yii::$app->request->isAjax && $modelUser->load(Yii::$app->request->post())){
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($modelUser);
}
if ($modelUser->load(Yii::$app->request->post()) && $modelUser->save()) {
return $this->redirect(['someplace nice']);
}
return $this->render('update', [
'modelUser' => $modelUser,
]);
}
模型
public function rules()
{
return [
..............
['email', 'unique', 'message'=>'Email already exist. Please try another one.'],
...........
]
}