简体   繁体   中英

Check url before redirect symfony2

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'));
    }

Did you check your cast? And are you sure about the route? usually route start with

'WEBSITENAME_'.$specific.'_thanks'

尝试这个:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM