0

currently I have a new action in my index.html.twig file.

        <div id="formcontent">
            form content goes here
        </div>
        <a href="{{ path('uni_new') }}">Create a new uni</a>

and my new action looks like this

 /**
 * Creates a new uni entity.
 *
 * @Route("/new", name="uni_new")
 * @Method({"GET", "POST"})
 */
public function newAction(Request $request)
{
    $uni = new Uni();
    $form = $this->createForm('AppBundle\Form\UniType', $uni);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($uni);
        $em->flush($uni);

        return $this->redirectToRoute('uni_show', array('id' => $uni->getId()));
    }

    return $this->render('uni/new.html.twig', array(
        'uni' => $uni,
        'form' => $form->createView(),
    ));
}

I want this new action to be done by ajax request. So when a user click on Create a new uni, instead of going to a new url, I want the form to be loaded by ajax call and replace the content of the above div with id formcontent. How can I do this? Thanks in advance.

1
  • The PHP code you displayed is OK overall, what you need is JS centric and has nothing to do with Symfony. You should probably add your JS code there. Commented Nov 29, 2016 at 23:25

2 Answers 2

1

For an ajax call, all a Symfony controller can do is responding the form HTML only with a json format.

/**
 * Creates a new uni entity.
 *
 * @Route("/new", name="uni_new")
 * @Method({"GET", "POST"})
 */
public function newAction(Request $request)
{
    $uni = new Uni();
    $form = $this->createForm('AppBundle\Form\UniType', $uni);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($uni);
        $em->flush($uni);

        /**
         * If your form also need a ajax submit, respond output accordingly.
         */

        return $this->redirectToRoute('uni_show', array('id' => $uni->getId()));
    }

    if ($request->isXmlHttpRequest()) {
        $formHtml = $this->renderView('uni/new.html.twig', array(
            'uni' => $uni,
            'form' => $form->createView(),
        ));
        return new JsonResponse(
            array(
                'success' => true,
                'formHtml' => $formHtml
            )
        );
    }

    return $this->render('uni/new.html.twig', array(
        'uni' => $uni,
        'form' => $form->createView(),
    ));
}

Use $request->isXmlHttpRequest() to detect if its an ajax call, and respond accordingly, The jQuery.ajax should take care of rest in terms of form replacement to the div.

Note : Code not tested.

Hope it helps!

Sign up to request clarification or add additional context in comments.

Comments

0
$(function () {
(function submitHandler() {
    var $form = $("#your_form_id");
    $form.on('submit', function (e) {
        e.preventDefault();
        $.ajax({
            type: $(this).attr('method'),
            url: $(this).attr('action'),
            data: $(this).serialize()
        })
            .done(function (data) {
                $form.replaceWith(data);
                submitHandler();
            })
            .fail(function (jqXHR) {
                if(jqXHR.status === 302) {
                    location.href = jqXHR.responseJSON;
                } else {
                    location.href = Routing.generate('registration_fail')
                }
            })
    })
})();

});

You have to add some js to your frontend. In this code I use JQUERY.

Some additional code in your Controller, when your form is Valid

if ($request->isXmlHttpRequest()) {
                return new JsonResponse($this->generateUrl('registration_success'), 302);
            }

You have to remember that Redirect in controller not working for You, when You use Ajax request, so you have to redirect your customer in frontend

Comments

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.