Yii2 activeform ajax提交和验证

时间:2015-07-14 21:39:00

标签: javascript php ajax yii2 active-form

目前同时实现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");
            }
        });

    });

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

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

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

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

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

3 个答案:

答案 0 :(得分:16)

使用 beforeSubmit 事件而不是提交,只有在表单通过验证后才会触发 beforeSubmit

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

答案 1 :(得分:10)

您可以使用AjaxSubmitButton

你的表格应该

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

在这里使用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(); 

在您的控制器中

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; 
     }
}

答案 2 :(得分:3)

Here我发现了一些有趣的javascript端验证技巧

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

触发:

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

动作控制器将回复:

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

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