【问题标题】:Zend Framework 2 RedirectZend Framework 2 重定向
【发布时间】:2015-04-30 21:04:23
【问题描述】:

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

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

这似乎不起作用,有什么想法吗?

【问题讨论】:

标签: zend-framework2


【解决方案1】:

这就是我从控制器重定向到另一个路由的方式:

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

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

最后 URL 变成 /dns/search/1(例如)

【讨论】:

  • 并确保您不会错过“return”关键字,因为如果您希望代码执行在没有它的情况下停止,那么可能会发生坏事;-)
【解决方案2】:

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

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

【讨论】:

  • BEST BEST BEST 最好的例子,这行得通,那是最好的。 return $this->redirect()->toUrl('/make-world-easy?id=thank-you');
  • 这个解决方案有不同的目的:它用于链接到其他资源。原则上,这并不重要,但如果您需要 Zend-ish 方法,则接受的答案是最好的。
【解决方案3】:

这是ZF2中的重定向方式:

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

希望对你有帮助。

【讨论】:

  • ModuleName 应该是RouteName
【解决方案4】:

Google 认为,这个问题与 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的smth

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    相关资源
    最近更新 更多