Search code examples
phpsymfonyhttp-redirectsymfony4

Symfony redirect in helper service does not work


Introduction

For my personal project i am using

  • Symfony v4.2 with
  • XAMPP and
  • Widows 10 Pro

In order to not to display route parameters in URL i save them in the table. Then in the controller i check if there is variable (that keeps UUID that corresponds to route parameters) in the session.

If i get no variable in session it should redirect to section start page, where UUID and initial data in the table are setup.

Redirect logic is extracted to helper service. In order to redirect to work there are copied functions redirectToRoute and redirect

I test this functionalit by deleting php session variables in temp folder and PHPSESSID cookie in the browser.

Problem

The prolem is - it does not redirect to secton start page.

I can see that correct if branch is selected, but then it "just stops" and does not execute redirect.

Code

public function checkWhereaboutsExist()
{
   $em = $this->entityManager;
   $repo_whereabouts = $em->getRepository(Whereabouts::class);

   $whereabouts = $this->session->get('whereabouts');
   if (($whereabouts === null) || ($whereabouts === ''))
   {
       $data = 'whereabouts === '.$whereabouts;
       dump($data);
       /*
       HERE IT STOPS
       */
       return $this->redirectToRoute('section_start');
   }
   else
   {
       $my_whereabouts = $repo_whereabouts->getWhereabouts($whereabouts);
       if (!$my_whereabouts)
       {
           return $this->redirectToRoute('section_start');
       }
   }
}

Question

Does enyone have some ideas about what is the culprit in this case?


Solution

  • You could try to inject the router into your service class:

    use Symfony\Component\Routing\RouterInterface;
    

    class MyService { private $router;

    public function __construct(RouterInterface $router)
    {
        $this->router = $router;
    }
    
    public function checkWhereaboutsExist()
    {
        // your code ...
    
        return new RedirectResponse($this->router->generate('section_start'));
    }
    

    }