Yii2: ajax form validation on an ajax submitted form

后端 未结 2 523
滥情空心
滥情空心 2021-02-01 09:28

I\'m wondering if any Yii2 experts can help me understand how best to work with ajax forms combined with Yii ajax validation. I think I can explain the issue without taking you

2条回答
  •  再見小時候
    2021-02-01 09:52

    I have found solution :

    Form :

      'form-add-contact', 'enableAjaxValidation' => true, 'validationUrl' => Yii::$app->urlManager->createUrl('contacts/contacts/contact-validate')]);
        ?>
    

    Submit Via Ajax :

    registerJs($script);
    ?>
    

    Controller :

    /*
         * CREATE CONTACT FORM  AJAX VALIDATION ACTION
         */
    
        public function actionContactValidate() {
            $model = new ContactsManagement();
            if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
                $model->company_id = Yii::$app->user->identity->company_id;
                $model->created_at = time();
                \Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            }
        }
    
    
    /**
         * Quick Add Contact Action
         * @param type $id
         * @return type
         */
        public function actionAddContact() {           
    
            $model = new ContactsManagement();
    
            if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
    
                $transaction = \Yii::$app->db->beginTransaction();
    
                try {
                    if ($model->validate()) {
                        $flag = $model->save(false);
                        if ($flag == true) {
                            $transaction->commit();
    
                            return Json::encode(array( 'status' => 'success', 'type' => 'success', 'message' => 'Contact created successfully.'));
                        } else {
                            $transaction->rollBack();
                        }
                    } else {
                        return Json::encode(array('status' => 'warning', 'type' => 'warning', 'message' => 'Contact can not created.'));
                    }
                } catch (Exception $ex) {
                    $transaction->rollBack();
                }
            }
    
            return $this->renderAjax('_add_form', [
                        'model' => $model,
            ]);
        }
    

提交回复
热议问题