0

在我的模态框中,我想检查唯一的电子邮件,这只能在提交表单后完成。当我触发提交按钮时,控制器操作将发送给我在控制器中创建操作,因为它将返回唯一的电子邮件地址错误。我希望这个错误显示在模态框中。所以我使用了Ajax提交。下面是我的代码。

我的表格

<?php yii\widgets\Pjax::begin(['class' => 'new_projects']) ?>
<?php $form = ActiveForm::begin([
        'action' => ['create'],
        'options' => ['class' => 'form-horizontal disable-submit-buttons', 'id'=> 'projectsId'],
             'fieldConfig' => [
                    'template' => "<div class=\"row .field-register-email\">
                                        <div class=\"col-xs-6 .help-block\">{label}</div>\n<div class=\"col-xs-6 text-right\">{hint}</div>
                                    \n<div class=\"col-xs-12 \">{input}</div>
                                    </div>",
                              ],
        ]); ?>

 <?= $form->errorSummary($model, $options = ['header'=>'']); ?>

            <?= $form->field($model, 'user_fname')->textInput(['class'=>'form-control']);?>
            <?= $form->field($model, 'user_lname')->textInput(['class'=>'form-control']); ?>
            <?= $form->field($model,'user_email',['enableAjaxValidation'=> 'true'])->textInput(['class'=>'form-control']); ?>
            <?= $form->field($model, 'user_password_hash')->passwordInput([]); ?>
            <?= $form->field($model, 'user_password_hash_repeat')->passwordInput(['class'=>'form-control']); ?>
            <?php  $items = ArrayHelper::map(SimAuthAssignment::find()->all(),'item_name' ,'item_name');?>
            <?= $form->field($mode, 'item_name')->dropDownList($items,[]);?>




<div class="form-group">
    <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>

<?php ActiveForm::end(); ?>
<?php yii\widgets\Pjax::end() ?>

我的控制器创建动作

 public function actionCreate()
    {
       $model = new SimUser(['scenario' => SimUser::SCENARIO_CREATE]);
       $mode = new \app\modules\auth\models\SimAuthAssignment();

        if ($model->load(Yii::$app->request->post()) && $mode->load(Yii::$app->request->post())){ 
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $model->setPassword($model->user_password_hash);
            $model->generateAuthKey(); 
            $model->company_id = Yii::$app->user->identity->company_id;
            if (!$model->save()){
                ($model->load(Yii::$app->request->post()) && $model->validate());
            }
            else{
            $auth = Yii::$app->authManager;
            $authorRole = $auth->getRole($mode->item_name);
            $auth->assign($authorRole, $model->getId());
             echo BaseJson::encode(array(
                "status"=>true,
                "message"=>"Created Project $model->name Successfully",
            ));
            }
        //    return $this->redirect(['index']);
        }  
            return $this->renderAjax('create', [
                'model' => $model,
                'mode' => $mode,
            ]);

    }

js文件

$(document).on("beforeSubmit", "#projectsId", function () {
    // submit form
    $.ajax({
        url    : $("#projectsId").attr('action'),
        type   : 'post',
        data   : $("#projectsId").serialize(),
        success: function(response)
        {
            alert("success");
            $.pjax.reload({container:"#projectsGrid"});
            $('#modal').modal("hide");
        },
        error  : function (response) 
        { 
            alert("failure");
            console.log('internal server error');
        }
        });
        return false;
        // Cancel form submitting.

});

我如何在模态框中出现错误。即使出现错误,也会触发警报(“成功”)。如果没有唯一的电子邮件,它就完美了。我想弄清楚如何使模态框出现错误。谢谢!!!

4

1 回答 1

1

在您的控制器更改代码中,如下所示:

use yii\bootstrap\ActiveForm;

public function actionCreate()
    {
       $model = new SimUser(['scenario' => SimUser::SCENARIO_CREATE]);
       $mode = new \app\modules\auth\models\SimAuthAssignment();

        if ($model->load(Yii::$app->request->post()) && $mode->load(Yii::$app->request->post())){ 
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $model->setPassword($model->user_password_hash);
            $model->generateAuthKey(); 
            $model->company_id = Yii::$app->user->identity->company_id;
            if ($model->validate()){
            $model->save();
            $auth = Yii::$app->authManager;
            $authorRole = $auth->getRole($mode->item_name);
            $auth->assign($authorRole, $model->getId());
             echo BaseJson::encode(array(
                "status"=>'true',
                "message"=>"Created Project $model->name Successfully",
            ));
            }
            else{

                $model=ActiveForm::validate($model);
                return['status'=>'false','errors'=>$model];

            }
        //    return $this->redirect(['index']);
        }  
            return $this->renderAjax('create', [
                'model' => $model,
                'mode' => $mode,
            ]);

    }

和你的 js 文件添加 yii 表单验证脚本:

 $(document).on("beforeSubmit", "#projectsId", function (e) {
e.stopImmediatePropagation(); 
        // submit form
        $.ajax({
            url    : $("#projectsId").attr('action'),
            type   : 'post',
            data   : $("#projectsId").serialize(),
            success: function(response)
            {
               if(response.status=="true")
               {
                $.pjax.reload({container:"#projectsGrid"});
                $('#modal').modal("hide");
                }
                else
                {

                 $('#projectsId').yiiActiveForm('updateMessages', 
                       response.errors
                    , true);
                }
            }
            });
            return false;
            // Cancel form submitting.
    });

更多参考https://github.com/samdark/yii2-cookbook/blob/master/book/forms-activeform-js.md

于 2016-07-19T09:18:54.613 回答