这唯一性验证怎么才能在view直接验证,我现在只能post到控制器里面validate后才能显示才能获取到错误信息。

view页面:开启ActiveForm的enableAjaxValidation,这样在表单输入之后就会请求服务器端,在服务端返回验证结果:

<?php $form = ActiveForm::begin([
    'action'=>"{$action}",
    'enableAjaxValidation' => true,//注意这里
    'options' => ['id'=>'form','class' => 'form-horizontal','autocomplete' => 'off'],
    'fieldConfig'=>[
        'template'=> "{label}\n<div class=\"col-sm-10\">{input}\n{error}</div>",
    ]
 ]) ?>
<div class="modal-body">
    <?= Html::activeHiddenInput($model,'id') ?>
    <div class="seleselinkage2">
        <?= $form->field($model,'username')->textInput()->label('员工姓名',['class'=>'col-sm-2 control-label']) ?>
        <?= $form->field($model,'account')->textInput(['autocomplete' => 'off'])->label('员工账号',['class'=>'col-sm-2 control-label']) ?>
    </div>
    <div class="seleselinkage2">
        <?= $form->field($model,'password')->passwordInput()->label('登陆密码',['class'=>'col-sm-2 control-label']) ?>
        <?= $form->field($model,'passwordRepeat')->passwordInput()->label('确认密码',['class'=>'col-sm-2 control-label']) ?>
    <div class="seleselinkage2">
    </div>
        <?= $form->field($model,'sex')->dropDownList(['1'=>'男','2'=>'女'])->label('性别',['class'=>'col-sm-2 control-label']) ?>
        <?= $form->field($model,'roleid')->dropDownList($rolelist)->label('角色',['class'=>'col-sm-2 control-label']) ?>
    <div class="seleselinkage2">
    </div>
        <?= $form->field($model,'identity')->textInput()->label('身份证号',['class'=>'col-sm-2 control-label']) ?>
        <?= $form->field($model,'tel')->textInput()->label('手机号',['class'=>'col-sm-2 control-label']) ?>
    </div>
    <div class="seleselinkage2">
    <?= $form->field($model,'isallowlogin')->dropDownList(['1'=>'允许','2'=>'不允许'])->label('允许后台登陆',['class'=>'col-sm-2 control-label']) ?>
        </div>
</div>
<div class="modal-footer">
    <?=Html::submitButton('保存',['class'=>'btn btn-primary'])?>
</div>
<?php ActiveForm::end() ?>

控制器代码如下:

public function actionCreate(){
    $model = new Employee();
    $model->setScenario('insert');
    $model->storeid = $this->storeid;
    //针对入库验证的返回操作
    $model->load(Yii::$app->request->post());
    if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
        Yii::$app->response->format = Response::FORMAT_JSON;
        return ActiveForm::validate($model);
    }

    if ($model->load(Yii::$app->request->post()) && $model->validate()) {
        $model->setPassword($model->password);
        $model->generateAuthKey();
        $model->generateAccessToken();
        if ($model->save()) {
            Yii::$app->session->setFlash('success', '添加成功“'.$model->username.'”。');
            return $this->redirect(['index']);
        } else {
            throw new Exception('员工添加失败!');
        }
    }
    $where['storeid'] = $this->storeid;
    $roleList = $this->role->getRoleList($where);
    return $this->renderAjax('form',[  'model' => $model,'rolelist'=>$roleList,'id'=>0]);
}

这样就会在入库之前,将异常拦截在弹窗的页面上了,不会进行页面跳转了!