if ($u = $this->generateUrl('_'.$specific.'_thanks'))
return $this->redirect($u);
else
return $this->redirect($this->generateUrl('_thanks'));
I wan't to redirect to the _specific_thanks
url when it exist. So How to check if a url exist?
When I did that, I had this error:
Route "_specific_thanks" does not exist.
I don't think there's a direct way to check if a route exists. But you can look for route existence through the router service.
$router = $this->container->get('router');
You can then get a route collection and call get()
for a given route, which returns null if it doesn't exist.
$router->getRouteCollection()->get('_'. $specific. '_thanks');
Using getRouteCollection()
on runtime is not the correct solution. Executing this method will require the cache to be rebuilt. This means that routing cache will be rebuilt on each request, making your app much slower than needed.
If you want to check whether 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!');
}
Try something like this, check 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'));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With