ZF2 - 使用post redirect get并重定向到带有params的URL

时间:2014-06-17 11:18:38

标签: zend-framework2

使用帖子ZF2 I管理Redirect Get上午的表单。有关此文档的文档可以在here找到。

到目前为止,我的重定向相对简单,我已经能够重定向到路由,但是我遇到了需要重定向到具有特定参数的特定URL的情况。

www.mysite.com/users/edit/id/1/page/4

路线是用户/编辑,我需要设置参数id = 1page = 4,以便在我编辑用户数据后,我会重定向回用户页面。

通常我的控制器看起来像这样::

    public function indexAction()
{
    $user_id = (int) $this->params()->fromRoute('id', 0);
    $page_id = (int) $this->params()->fromRoute('page', 0);

    $prg = $this->prg('users/edit');

    //If user has posted, execute the re-direct
    if ($prg instanceof Response) {
        return $prg;
    } elseif ($prg === false) {
        //First time form has been loaded set the view
    }

   //User has hit submit, do submit stuff here

以上示例无效,因为redirect不是re-directing带有参数的网址。要使其工作,您需要更新以下::

Replace:: $prg = $this->prg('/user/edit/id');

要::

$prg = $this->prg('/user/edit/id/'.$user_id.'/page/'.$page_id.'',true);

True将PRG切换为ROUTE ...

中的URL

现在,当用户提交数据时,他们将被重定向到定义的URL。

当然你可以简单地设置一个邮政路线......但是你需要不止一个动作......

这是我的解决方案,我无法找到更好的方法来做到这一点。所以我的问题很简单,有没有更好的方法呢?

1 个答案:

答案 0 :(得分:1)

这是PRG的一个错误。它可以处理以下情况:

  1. 重定向到网址(没有路由名称,该路由的网址)
  2. 重定向到不带参数的路由
  3. 重定向到当前匹配的路线
  4. 对于第一个场景,您必须传递true作为第二个参数。

    // True to keep matched params
    $url = $this-url()->fromRoute('foo/bar/baz', array(), true); 
    
    // True to note PRG it's a URL, no route name
    $prg = $this->prg($url, true); 
    

    对于第二种情况,它是最常见的情况:

    $prg = $this->prg('foo/bar/baz');
    

    最后一个场景使用当前选定的路线。我们经常对具有参数的路由执行此操作,其中路由参数必须重复使用,并且我们PRG到相同的路径:

    $prg = $this->prg();
    

    如果您有要应用PRG的路线,并且此路线包含路线匹配参数,我建议您使用null(或者,不要提供任何参数)。如果这条PRG路线与您当前使用的路线不同,则必须提供该网址。

相关问题