Home > OS >  Form redirect for confirmation
Form redirect for confirmation

Time:05-22

Form redirect for confirmation can be currently managed using one of these two options:

1/ Flash message: using flashbag on the form page or another page like this:

$this->addFlash('success', 'Thank you');
return $this->redirectToRoute('confirmation_page');

2/ Confirmation page: using a dedicated confirmation like this:

return $this->redirectToRoute('confirmation_page');

BUT using option 2 makes the confirmation_page directly accessible from the browser without having submitted the form before. I am currently using flashbag mechanism to fix it by adding a $this->addFlash('success', true); before the redirection in the form and then checking the flashbag content in the confirmation page so that the route is accessible only once after being successfully redirected from the form.

Is there any best practice or more appropriate way to manage it?

   /**
     * @Route("/confirmation", methods="GET", name="confirmation_page")
     */
    public function confirmation(): Response
    {
        $flashbag = $this->get('session')->getFlashBag();
        $success = $flashbag->get("success");

        if (!$success) {
            return $this->redirectToRoute('app_home');
        }

        return $this->render('templates/confirmation.html.twig');
    }

CodePudding user response:

Flash Message is designed to display messages. Instead, use sessions in your application.

When submitting the confirmation form, create a variable in the session before the redirect

$this->requestStack->getSession()->set('verifyed',true);
return $this->redirectToRoute('confirmation_page');

Use the created variable in your method

public function confirmation(): Response
{  
    if (!$this->requestStack->getSession()->get('verifyed')) {
        return $this->redirectToRoute('app_home');
    }

    return $this->render('templates/confirmation.html.twig');
}

Don't forget to inject the RequestStack into your controller

private RequestStack $requestStack;

public function __construct(RequestStack $requestStack)
{
    $this->requestStack = $requestStack;
}
  • Related