Zend Framework 2 重定向

10

我该如何重定向到另一个模块?

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
4个回答

27

这是我如何从控制器重定向到另一个路由的方法:

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

其中dns-search是我想要重定向的路由,companyid是url参数。

最终URL变为/dns/search/1(例如)


2
请确保不要错过那个“return”关键字,如果您期望代码在没有它的情况下停止执行,可能会发生糟糕的事情;-) - AlexMA

17

重定向的一种简单方法是:

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

1
最好的例子,这个可行并且是最好的。return $this->redirect()->toUrl('/make-world-easy?id=thank-you'); - user285594
1
这个解决方案用于链接到其他资源,目的与之前不同。原则上,这并不真正重要,但如果需要 Zend 风格的方法,接受的答案是最好的选择。 - Dima Dz

6

This is the way of redirection in ZF2:

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

我希望这能对你有所帮助。

5
ModuleName 应该改为 RouteName - Lukas Ignatavičius

1
谷歌认为这个问题与 zf2 redirect with anchor 相关,因此我会在这里添加答案,如果您不介意的话。我们可以在 toRoute 的第三个参数中使用 fragment 选项:
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',
        ),
    ),
),

所以,用户将被导向类似于/chats/view/12/#m134的页面。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接