Javascript Yii2 activeform ajax提交和验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31417868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:41:26  来源:igfitidea点击:

Yii2 activeform ajax submit and validation

javascriptphpajaxyii2active-form

提问by heron

Currently to achieve ajax submit and validation at the same time. I'm using custom function like:

目前实现ajax提交和验证同时进行。我正在使用自定义函数,如:

    $('.edit_form').submit(function (e) {
        e.preventDefault();
        var form = $(this);
        var formData = $(this).serialize();
        if (form.find('.has-error').length) {
            return false;
        }

        $.ajax({
            url: form.attr("action"),
            type: form.attr("method"),
            data: formData,
            success: function (data) {
                 ...
            },
            error: function () {
                alert("Something went wrong");
            }
        });

    });

And here is php side, for validation my config looks like that:

这是php方面,为了验证我的配置看起来像这样:

$form = ActiveForm::begin([
    'id' => "some_form",
    'action' => ['user/edit'],
    'options' => ['class' => 'edit_form'],
    'enableAjaxValidation' => false,
    'enableClientValidation' => true,
]); ?>

I'm sure that It's not the best way to achieve what I need. Especially this part that I use for preventing for submission in case of validation error:

我确信这不是实现我所需要的最佳方式。特别是我用来防止在验证错误的情况下提交的这部分:

    if (form.find('.has-error').length) {
        return false;
    }

Any suggestions? How to achieve ajax submission and validation properly using Yii 2's inbuilt settings?

有什么建议?如何使用 Yii 2 的内置设置正确实现 ajax 提交和验证?

回答by Nader

Use beforeSubmitevent instead of submit, the beforeSubmitwill only be triggered once the form passes the validation.

使用beforeSubmit事件而不是submitbeforeSubmit只会在表单通过验证时触发。

$('form').on('beforeSubmit', function(e) {
    var form = $(this);
    var formData = form.serialize();
    $.ajax({
        url: form.attr("action"),
        type: form.attr("method"),
        data: formData,
        success: function (data) {
             ...
        },
        error: function () {
            alert("Something went wrong");
        }
    });
}).on('submit', function(e){
    e.preventDefault();
});

回答by Dhara

you can use AjaxSubmitButton.

你可以使用AjaxSubmitButton

Your form should b

你的表格应该是

$form = ActiveForm::begin([
    'id' => "some_form",
    'action' => 'javascript:void(0)',
    'options' => ['class' => 'edit_form'],
]);

use AjaxSubmitButton here

在这里使用 AjaxSubmitButton

AjaxSubmitButton::begin([
                                'label' => 'Submit',
                                'id' => 'some_form',
                                'ajaxOptions' => [
                                    'type' => 'POST',
                                    'url' => \yii\helpers\Url::to(['/user/edit']),
                                    'success' => new \yii\web\JsExpression(
                                            'function(data){
                                                if(data=="success")
                                                    {
                                                    }else{
                                                        $.each(data, function(key, val) {
                                                            $("#"+key).after("<div class=\"help-block\">"+val+"</div>");
                                                            $("#"+key).closest(".form-group").addClass("has-error");
                                                        });
                                                    }
                                                }'
                                    ),
                                ],
                                'options' => ['class' => 'btn btn-success', 'type' => 'submit'],
                            ]);
                            AjaxSubmitButton::end(); 

In your controller

在您的控制器中

public function actionEdit()
{
     $model = new User;
     if($model->save())
     {
        $result = 'success';
        Yii::$app->response->format = trim(Response::FORMAT_JSON);
                return $result;
     }else{
         $error = \yii\widgets\ActiveForm::validate($model);
                Yii::$app->response->format = trim(Response::FORMAT_JSON);
                return $error; 
     }
}

回答by letsjump

HereI've find some interesting javascript-side validation tricks

在这里,我发现了一些有趣的 javascript 端验证技巧

So, a javascript submit button can be as:

所以,一个 javascript 提交按钮可以是:

$('body').on('click', '#submit', function(e) {
  e.preventDefault();
  var yiiform = $('#my-form');
  $.ajax({
    type: yiiform.attr('method'),
      url: yiiform.attr('action'),
      data: yiiform.serializeArray(),
      success: function(data) {
        if(data.success == 'true') {
          window.location.href = 'http://my.success.page';
        } else {
          // here there is (maybe) the right way to trigger errors
          $.each(data, function(key, val) {
            yiiform.yiiActiveForm('updateAttribute', key, [val]);
          });
        }
      }
  });
}

triggered by:

触发:

<?= Button::widget([
    'label' => Yii::t('app', 'Submit'),
     'options' => [
        'id'=>'submit',
        'class' => 'btn btn-primary pull-right',
     ]]);?>

And the action controller will reply with:

动作控制器将回复:

...
if ($model->load(Yii::$app->request->post())) {
    Yii::$app->response->format = Response::FORMAT_JSON;
    if($model->save()) {
        return ['success'=>'true'];
    } else {
        return ActiveForm::validate($model);
    }
}
...

Details about ActiveForm::validate() can be found here

可以在此处找到有关 ActiveForm::validate() 的详细信息