0

In my Modal box I want to check for unique email, which can be done only after submitting the form. When I trigger thee submit button the controller action will send me to create action in the controller because it will return unique email address error. I want this error to be displayed in the modal box. So I used Ajax submission. Here is my code below.

My form

<?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() ?>

My Controller Create Action

 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 file

$(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.

});

How do i get errors in my modal box. Even if there are errors the alert("success") is triggered. If there is no unique email, it works perfect. I want to figure out how to make get the error to the modal box. Thanks!!!

Mohan Prasad
  • 682
  • 1
  • 9
  • 34

1 Answers1

1

in your controller change code like below:

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,
            ]);

    }

and your js file add yii form validation script:

 $(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.
    });

for more reference https://github.com/samdark/yii2-cookbook/blob/master/book/forms-activeform-js.md

jithin
  • 920
  • 9
  • 17
  • I have no idea.. Even if there are errors it give alert:success.... only if it triggers error it would be possible to dispaly error.. – Mohan Prasad Jul 19 '16 at 09:26
  • There should be a "model->validate()" in the controller which will send back the error messages to the view. but when i add them It breaks the code. – Mohan Prasad Jul 19 '16 at 09:36
  • @MohanPrasad "only if it triggers error it would be possible to dispaly error" no i added littile bit changes in controller and js file code please check – jithin Jul 19 '16 at 09:57
  • if there is no unique email, what it does is it submits the form and immediately throws error message – Mohan Prasad Jul 19 '16 at 10:24
  • @MohanPrasad any error message is showing in your ajax response (response.error) – jithin Jul 19 '16 at 13:12
  • ya it is showing up in that .. but when there is no unique email what happens is, I create the user, it returns true. It should hide the modal but instead it created the user and immediately runs the js again and shows the error message your email has been taken? – Mohan Prasad Jul 19 '16 at 13:33
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/117727/discussion-between-mohan-prasad-and-jithin). – Mohan Prasad Jul 19 '16 at 15:04