从数据库唯一验证中验证唯一值
如果正在输入现有值,则有些人会出现有关错误消息未显示的问题。例如,我不允许用户注册现有的电子邮件。
视图
<?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.'],
...........
]
}