Search code examples
symfonysymfony5

Go back button submits the form


I'm currently having issues with my user's update form in Symfony. It's all working good but when it comes to the button part there is a problem.

In my twig template I got this :

<div>
     <button onClick="window.history.back();">Go back</button>
     <button type="submit">Update</button>
</div>

When I click on the Update button it works and my user is updated but when I click it works too when I click on the Go back button, I'm redirected to the previous page but it sumbits the form. I don't want the Go back button to sumbit the form, how can I do that ?

Thanks for your help.

EDIT : There is my controller function for the update page

/**
* @Route("/admin/users/{id}/update", name="usersUpdate", methods={"GET","POST"})
* @IsGranted("ROLE_ADMIN")
*/
public function usersUpdate(User $user, Request $request)
{
    $form = $this->createForm(RegistrationFormType::class, $user);
    $form->remove('plainPassword');
    $form->handleRequest($request);

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

        $this->container->get('session')->getFlashBag()->add('validUpdate', 'L\'utilisateur a été mis a jour.');
        return $this->redirectToRoute('users');
    }

    return $this->render('admin/users/update.html.twig', [
        'registrationForm' => $form->createView()
    ]);
}

Solution

  • Jakumi and Yoshi figured it out !

    It was due to the type of the button. Adding type="button" to the Go back button was the solution.


    Their answers :

    I believe the default type of a button is submit. you should explicitly state type="button" for the back button. see developer.mozilla.org/en-US/docs/Web/HTML/Element/button for details. - Jakumi

    and

    You need to specify <button onClick="window.history.back();">Go back</button> as <button onClick="window.history.back();" type="button">Go back</button>. Otherwise it defaults to sumbit when the button is placed inside <form/>. Ref: developer.mozilla.org/en-US/docs/Web/HTML/Element/button - Yoshi