如何在ajax查询和JsonResponse之后显示表单错误

时间:2016-04-12 10:14:15

标签: json ajax symfony

我有一个使用jquery和ajax添加产品的表单。添加prouct工作正常,但我想知道如何使用JsonRespone显示表单错误 这是jquery代码

$(document).on('submit', "#form-add", function (e) {
            e.preventDefault();
            $.ajax({
                type: 'post',
                dataType: 'json',
                data: $(this).serialize(),
                url: Routing.generate('admin_add_product'),
                success: function (msg) {

                },
                error: function(msg){
                   // do something to display errors
                }
            });

            return false;

        });

这就是行动

public function addAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();
    $product = new Product();
    $form = $this->createForm(new ProductType(), $product);
    if ($request->isXmlHttpRequest()) {
        if ($request->getMethod() == 'POST') {
            $form->handleRequest($request);
            if ($form->isValid()) {
                $em->persist($product);
                $em->flush();
                $this->get('session')->getFlashBag()->add('success', 'Your product has been added to your cart.');

                $response = new JsonResponse();
                return $response;
            } else {
                // return errors
            }
        }
    }

}

0 个答案:

没有答案