2013-03-08 98 views
9

如何重定向到另一個模塊?Zend Framework 2重定向

return $this->redirect()->toRoute(null, array(
    'module'  => 'othermodule', 
    'controller' => 'somecontroller', 
    'action'  => 'someaction' 
)); 

這似乎不工作,有什麼想法?

+2

如果您要重定向,重定向到路線名稱。如果您只想分派另一個操作,請使用forward()助手。請參閱http://framework.zend.com/manual/2.1/en/modules/zend.mvc.plugins.html – Sam 2013-03-08 22:04:40

回答

24

這是我從我的控制器重定向到另一個途徑:

return $this->redirect()->toRoute('dns-search', array(
    'companyid' => $this->params()->fromRoute('companyid') 
)); 

當DNS搜索是我要重新導向和companyid路線是網址參數。

在URL變爲/ DNS /搜索/ 1(例如)

+0

並確保您不會錯過「return」關鍵字,因爲如果您期望執行代碼,可能會發生壞事在沒有它的地方停下來;-) – AlexMA 2014-09-19 16:19:58

6

這是重定向在ZF2的方式結束:

return $this->redirect()->toRoute('ModuleName', 
    array('controller'=>$controllerName, 
     'action' => $actionName, 
     'params' =>$params)); 

我希望這可以幫助你。

+3

'ModuleName'應該是'RouteName' – 2014-07-25 08:07:10

16

其中一個簡單的方法來重定向是:

return $this->redirect()->toUrl('YOUR_URL'); 
+1

BEST BEST BEST最好的例子,這工作,這是最好的。 'return $ this-> redirect() - > toUrl('/ make-world-easy?id = thank-you');' – YumYumYum 2016-10-26 23:39:40

+0

這個解決方案是爲了不同的目的:它用於鏈接到其他資源。原則上,這並不重要,但如果您需要Zend-ish方法,則接受的答案是最好的。 – 2017-01-28 08:14:59

1

谷歌認爲,這個問題是有關ZF2錨重定向,所以我會在這裏添加的答案,如果你不介意。我們可以只使用fragment選項的toRoute第三個參數:

public function doAction(){ 
    return $this->redirect() 
     ->toRoute('chats', 
        array('action' => 'view', 
         'id' => $message->getChat()->getId() 
        ), 
        array('fragment' => 'm' . $message->getId()) 
    ); 
} 

我的路線:

'chats' => array(
    'type' => 'segment', 
    'options' => array(
     'route' => '/chats/[:action/][:id/]', 
     'constraints' => array(
      'action' => '[a-zA-Z][a-zA-Z0-9_-]*', 
      'id' => '[0-9]+', 
     ), 
     'defaults' => array(
      'controller' => 'Application\Controller\Chats', 
      'action' => 'index', 
     ), 
    ), 
), 

因此,用戶將被引導到SMTH像/chats/view/12/#m134