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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With