(1) List up errors
if( $form->isValid() ) {
// ...
} else {
// get a ConstraintViolationList
$errors = $this->get('validator')->validate( $user );
$result = '';
// iterate on it
foreach( $errors as $error ) {
// Do stuff with:
// $error->getPropertyPath() : the field that caused the error
// $error->getMessage() : the error message
}
}
(2) Frontend
$.extend({
ajaxData: function($button, options) {
var defaultOptions = {
type: 'POST', beforeSend: function() {
$button.prop('disabled', true); }, complete: function() {
$button.prop('disabled', false); }, success: function(data) {
window.location.reload(); }, error: function(xhr) {
if (xhr.responseJSON) {
for (k in xhr.responseJSON) {
msg = xhr.responseJSON[k]; if(k == '_global') {
} else {
$('[name="'+k+'"]').after($('<span class="error" />').text(msg)); }
}
}
}
};
$.ajax($.extend({}, defaultOptions, options)); }
});
(3) Backend
private function getFormErrors($form)
{
$errors = array('_global' => array()); foreach ($form->getErrors() as $e) {
$errors['_global'][] = $e->getMessage(); }
foreach ($form as $field) {
if (!$this->hasError($field)) {
continue; }
$view = $field->createView();
$fieldErros = $field->getErrors(); foreach ($fieldErros as $e) {
$errors[$view->vars['full_name']] = $e->getMessage(); }
}
return $errors;}
private function hasError($field)
{
if (count($field->getErrors()) > 0) {
return true; }
foreach ($field as $child) {
if ($this->hasError($child)) {
return true; }
}
return false;}
Comments
Post a Comment