2

I have a form to add product using jquery and ajax. Adding proucts work fine but I'd like to know how to display form errors with JsonRespone This is the jquery code

$(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;

        });

and this is the action

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
            }
        }
    }

}
hous
  • 2,577
  • 2
  • 27
  • 66
  • 1
    http://stackoverflow.com/a/24606082/2324004 – eRIZ Apr 12 '16 at 10:36
  • 1
    Possible duplicate of [how to return json encoded form errors in symfony](http://stackoverflow.com/questions/24556121/how-to-return-json-encoded-form-errors-in-symfony) – eRIZ Apr 12 '16 at 10:36
  • 1
    check [this](http://stackoverflow.com/a/34069322/2270041) answer also for a complete working example – Matteo Apr 12 '16 at 10:41
  • @Matteo , thank you it works good. I'd like to fetch errors in a separate view **errors.html.twig** and return it in the JsonResponse. I can do that an display the view with jquery but can't understand how to change this javascript loop `for (var key in data.data) { $(form.find('[name*="'+key+'"]')[0]).before('
    • '+data.data[key]+'
    '); }` to twig code. I tried this but doesn't work `{% for error in data %} {{ error }} {% endfor %}`
    – hous Apr 12 '16 at 12:21

0 Answers0