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

}
4
  • 1
    stackoverflow.com/a/24606082/2324004 Commented Apr 12, 2016 at 10:36
  • 1
    Possible duplicate of how to return json encoded form errors in symfony Commented Apr 12, 2016 at 10:36
  • 1
    check this answer also for a complete working example Commented Apr 12, 2016 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('<ul class="errors"><li>'+data.data[key]+'</li></ul>'); } to twig code. I tried this but doesn't work {% for error in data %} {{ error }} {% endfor %} Commented Apr 12, 2016 at 12:21

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.