4

i have a form in Symfony2 which i validate with ajax. This is all working, and i get back a json with "global" (for global errors) and "fields" (errors for each field in here) in my success statement of the ajax call:

{"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"}}

My question is: What is the best way to present these errors from "fields" in the view for each field? I rendered the view elements as the following when i validated the form without ajax:

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

How can i inject now the errors from the "field" list of my json object into the appropriate

{{ form_errors(form.xyz) }}

?

I would love to hear your ideas and best practices.

Regards.

1 Answer 1

7

You add them via Javascript/jQuery.

I've a similar situation and this is my code:

The Js code that post form data and show errors messages in case of errors.

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

   });
}

Here is my Json in case of error. Is the standard one you get if you use 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."
            ]
         }
      }
   }
}

The HTML for my form is

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

If you need more details just ask

Sign up to request clarification or add additional context in comments.

3 Comments

Hi, thanks for this answer. Was really helpful. I got a question on my controller. I was using the FosUserBundle RegistrationController. I've overwritten it and "minimalized" the registerAction method to only render the blank registration form first. I have outsourced the logic to validate the form into another method for the ajax request. So my registerAction() creates an empty user object , that the fields are displayed and rendered.And then in the validateRegistrationAction() i create another new user object that gets validated with the form data. Is this the right way to do that ? Regards.
Well, this is not related to your first question. Please accept my response if you think is correct and post a new one.
Hi, i accepted your answer. No you are wrong, it is related. It is the controller that sends me back the json answer. Is my architecture right ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.