我正在尝试创建一个好的验证js< => Symfony2,我提出了所有错误的集合,并创建了一个id表单元素的路径,一切看起来它正常工作,包括关系和集合形式,我的问题是你是否可以做一些更好的事情? Symfony可以捆绑一下吗?哪个比我的代码更有用?
//在控制器中
$ajax = $request->request->get('ajax');
if($form->isSubmitted() && $form->isValid() && !$ajax){
} elseif($form->isSubmitted() && !$form->isValid() && $ajax){
$serializer = $this->get('serializer');
return new JsonResponse(array(
'valid' => false,
'errors' => $serializer->serialize(
$form->getErrors(true),
'json')
));
}
//和js
$('form[name="product"]').on('submit',function(){
var data = $(this).serialize();
data = data + '&ajax=true';
$.ajax({
method: "POST",
url: Routing.generate('shop_add_products', { slug: $(this).data('slug') }),
data: data
})
.done(function( msg ) {
//there i must write check if errors then not return false and allow normall process form
$('input,textarea,select').parent().removeClass('has-error').find('span.help-block').remove();;
var errors = JSON.parse(msg.errors);
var filteredErrors = [];
var mappedErrors = [];
for(var k in errors){
filteredErrors[errors[k].messageTemplate] = errors[k].message;
var selector;
var path = errors[k].cause.propertyPath.split('.');
if(path.length == 2){
selector = 'product_' + path[1];
} else {
var path1 = path[0].replace('children[','');
path1 = path1.replace(']','');
var path2 = path[1].replace('data[','');
path2 = path2.replace(']','');
selector = 'product_' + path1 + '_' + path2 + '_' + path[2];
}
var helper = '<span class="help-block">' + errors[k].message + '</span>';
$('#' + selector).parent().addClass('has-error').append(helper);
}
});
return false;
});
如何通过ajax发送有效文件并将其映射到此功能? See there