Check URL before redirecting symfony2

if ($u = $this->generateUrl('_'.$specific.'_thanks')) return $this->redirect($u); else return $this->redirect($this->generateUrl('_thanks')); 

I will not redirect the _specific_thanks if it exists. So how to check if a url exists?

When I did this, I had this error:

The route "_specific_thanks" does not exist.

+7
php symfony routing
source share
5 answers

I don't think there is a direct way to check if a route exists. But you can search for the existence of a route through a router service.

 $router = $this->container->get('router'); 

Then you can get a collection of routes and call get() on the given route, which returns null if it does not exist.

 $router->getRouteCollection()->get('_'. $specific. '_thanks'); 
+11
source share

Using getRouteCollection() at run time is not the right solution. To perform this method, you need to reinstall the cache. This means that routing caching will be rebuilt on every request, which will make your application much slower than necessary.

If you want to check if a route exists or not, use the try ... catch construct:

 use Symfony\Component\Routing\Exception\RouteNotFoundException; try { dump($router->generate('some_route')); } catch (RouteNotFoundException $e) { dump('Oh noes, route "some_route" doesn't exists!'); } 
+9
source share

Try something like this, check if the route exists in the array of all routes:

  $router = $this->get('router'); if (array_key_exists('_'.$specific.'_thanks',$router->getRouteCollection->all())){ return $this->redirect($this->generateUrl('_'.$specific.'_thanks')) } else { return $this->redirect($this->generateUrl('_thanks')); } 
+1
source share

Have you checked your cast? And are you sure about the route? usually start the route with

  'WEBSITENAME _'. $ Specific .'_ thanks' 
0
source share

Try the following:

 if ($u == $this->generateUrl('_'.$specific.'_thanks') ) 
-3
source share

All Articles