2015-12-30 62 views
1

我想學習symfony,並開始創建一個小應用程序。我有一個與路線有關的問題。所以,我有我的項目中路線:在symfony2中檢查路由

/admin/homepage/admin/newsadmin/galery

沒有,如果我在URL /admin寫,這條路並不存在,我得到的錯誤No route found for "GET /admin/"。存在一種方法來檢查路由是否不存在並重定向到另一個路由? THX提前對不起我的英語 我的路線:

news_all: 
path: /news/all/{page} 
defaults: { _controller: AppAdminBundle:News:all, page: 1 } 
requirements: 
    page: \d+ 
    _method: GET|POST 
news_add: 
path: /news/add 
defaults: { _controller: AppAdminBundle:News:add } 
+0

您可以添加'indexAction'並將重定向添加到所需的函數中。 – AnkiiG

+0

您是如何在控制器中定義路線的? – KhorneHoly

+0

我編輯了這個問題 –

回答

0

在你的情況下,最好的解決辦法是覆蓋默認ExceptionController並添加自定義邏輯存在,例如重定向到其他頁面 - 根據文檔:http://symfony.com/doc/current/cookbook/controller/error_pages.html#overriding-the-default-exceptioncontroller

# app/config/config.yml 
twig: 
    exception_controller: AppBundle:Exception:showException 

注: 而是從頭開始創建一個新的異常控制器就可以了,當然,也延長了默認ExceptionController。在這種情況下,您可能想要覆蓋showAction()findTemplate()方法中的一個或兩個。後者定位要使用的模板。

+0

對不起,但我不明白如果我將加入一條不存在的路由,重定向怎麼辦 –

+0

當你訪問不存在的路由時,會觸發'HttpNotFoundException',而不是那個異常被' Symfony2'異常監聽器和'ExceptionConttroller'將被調用。所有你需要做的就是實現你自定義的'ExceptionController',並用簡單的'$ this-> redirectToToute('your_route')'將用戶重定向到合適的路線。 –

0

的Symfony的好的做法是設置在擊潰你的控制器,使用註解

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; 

/** 
* @Route("/news/add", name="news_add") 
*/ 
public function addAction() 
{ 
    // ... 
} 

而且,與註釋,您可以爲整個控制器設置潰敗。 就你而言,這就是你要找的東西。

/** 
* @Route("/admin") 
*/ 
class NewsController extends Controller 
{ 
    /** 
    * @Route("/news/add", name="news_add") 
    */ 
    public function addAction() 
    { 
     // ... 
    } 
} 

此外,我建議你看看@Template annotation

否則,要回答您的問題,我認爲您可以製作自定義的小枝功能(有關更多信息,請參閱this link)。檢查函數是給定名稱的有效路由:

function routeExists($name) 
{ 
    // I assume that you have a link to the container in your twig extension class 
    $router = $this->container->get('router'); 
    return (null === $router->getRouteCollection()->get($name)) ? false : true; 
} 
+0

你能幫忙嗎? http://stackoverflow.com/questions/39715888/symfony-2-router-with-parameter-returns-404/ – Volatil3