Symfony2 ajax表单验证在树枝中渲染错误

时间:2014-11-05 23:19:51

标签: php jquery ajax forms symfony

我在Symfony2中有一个表单,我用ajax验证。这一切都正常,我在ajax调用的成功声明中找回了一个带有“global”(全局错误)和“fields”(这里的每个字段的错误)的json:

{"global":[],"fields":{"fos_user_registration_form_username":"Please enter a 
username","fos_user_registration_form_email":"Please enter an 
email","fos_user_registration_form_plainPassword_first":"Please enter a password"}}

我的问题是:在每个字段的视图中,从“字段”中显示这些错误的最佳方法是什么?当我验证没有ajax的表单时,我将视图元素渲染为:

 <div class="form-group">
   {{ form_label(form.xyz) }}
   {{ form_widget(form.xyz) }}
   {{ form_errors(form.xyz) }}
 </div>

如何将我的json对象的“field”列表中的错误注入相应的

{{ form_errors(form.xyz) }}

我很想听听您的想法和最佳做法。

问候。

1 个答案:

答案 0 :(得分:7)

您可以通过Javascript / jQuery添加它们。

我有类似的情况,这是我的代码:

发布表单数据并在出现错误时显示错误消息的Js代码。

$.ajax({

    url : $(this).attr('action') + ".json",
    method : 'POST',
    data : $(this).serialize(),

}).done(function(data) {

        // Code in case of success

}).fail(function(jqXHR) {

   $.each(jqXHR.responseJSON.errors.children, function(k, v) {

       errorsText = "";

       if ((v.errors) && (v.errors.length > 0)) {
           $.each(v.errors, function(n, errorText) {
               errorsText += errorText;
           });
           $('#form_'+k).tooltip('destroy');
           $('#form_'+k).tooltip({'title': errorsText});    
           $('#form_'+k).closest('div[class="form-group"]').addClass('has-error');
        } else {
           $('#form_'+k).closest('div[class="form-group has-error"]').removeClass('has-error');
           $('#form_'+k).tooltip('destroy');
      }

   });
}

如果出现错误,这是我的Json。如果您使用FOSRestBundle

,则是您获得的标准版
{
   "code":400,
   "message":"Validation Failed",
   "errors":{
      "children":{
         "name":{
            "errors":[
               "This value should not be blank."
            ]
         }
         "email":{
            "errors":[
               "This value should not be blank."
            ]
         }
         "privacy":{
            "errors":[
               "This value should not be blank."
            ]
         }
      }
   }
}

我的表单的HTML是

<form id="sfForm" action="/landingbuilder/landing/test_template" method="POST">

    <div class="form-group">
        <label class="control-label required" for="form_name">Name</label>
        <input type="text" id="form_name" name="form[name]" required="required" class="form-control" />
    </div>

    [..]

</form>

如果您需要更多详细信息,请询问

相关问题