Created
September 10, 2013 06:27
-
-
Save Graceas/6505670 to your computer and use it in GitHub Desktop.
Symfony 2 used FormErrorsSerializer.php with jQuery.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function form_callback(target) | |
{ | |
target = $(target); | |
$.ajax({ | |
url: target.attr('action'), | |
type: target.attr('method'), | |
data: target.serialize(), | |
dataType: 'json', | |
beforeSend: function() { | |
//clear errors | |
target.find('.alert-error').remove(); | |
//disable buttons | |
target.find('[type="submit"]').attr('disabled', 'disabled'); | |
}, | |
success: function(response) { | |
target.find('[type="submit"]').removeAttr('disabled'); | |
if (response.status == 'error') { | |
//process errors | |
process_errors(target, response.errors); | |
} else { | |
if (response.status == 'redirect') { | |
window.location.href = response.redirect; | |
} else { | |
//stay down | |
if (response.status == 'data') { | |
target.html($(response.data)); | |
} | |
} | |
} | |
} | |
}); | |
return false; | |
} | |
function process_errors(target, errors) | |
{ | |
if (target.find('.global-errors-container').length > 0) { | |
for (var i in errors.global) { | |
target.find('.global-errors-container').append( | |
'<div class="alert-error">' + errors.global[i] + '</div>' | |
); | |
} | |
} | |
for (var field_id in errors.fields) { | |
if ($('#' + field_id).length > 0) { | |
$('#' + field_id).before( | |
'<div class="alert-error">' + errors.fields[field_id] + '</div>' | |
); | |
} | |
} | |
} |
Thanks. Nice one and handy code snippet of controller and form code. I have gone through your example. I found only server side validation you managed in this approach.
Can you please let me know or give me idea for how to manage client side validation as well?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add 'onsubmit' handler to your form:
< form class="form" action="{{ path('...') }}" method="POST" onsubmit="form_callback(this); return false;" >