简体   繁体   English

Symfony2:重定向到请求的路径

[英]Symfony2: Redirect to requested path

I want to redirect the user back to the path from which he started the request. 我想将用户重定向回他发起请求的路径。

Example: /profile 示例:/ profile

/profile/edit /个人资料/编辑

/profile /轮廓

OR: 要么:

/products /产品

/profile/edit /个人资料/编辑

/products /产品

What do I have to set for this redirection mode? 我必须为该重定向模式设置什么?

Inside your controller for /profile/edit you can capture the page they came from with $request->headers->get('referer') . /profile/edit的控制器内,您可以使用$request->headers->get('referer')捕获它们来自的页面。

If /profile/edit is a page with a single form, I'd probably just add a hidden field that says where the redirect should go. 如果/profile/edit是具有单一表单的页面,则可能只需要添加一个隐藏字段,指明重定向的位置。

public function editAction(Request $request)
{
    // If you have a POST value coming from the user, it will be used, otherwise
    // assume this is the first time they landed on the page and grab the current 
    // referer. With this method it doesn't matter how many times they submit the form
    // you won't accidentally overwrite the referer URL with /profile/edit. That could
    // lead to a confusing loop.
    $referer = $request->request->get('referer', $request->headers->get('referer'));

    if ($formIsSaved)
    {
        return new RedirectResponse($referer)
    }

    return array(
        // Your template should include a hidden field in the form that returns this.
        'referer' => $referer,
    );
}

You could pass a redirect path as a GET parameter — say, redirectTo — to the edit page and after the edit process is complete, redirect to that path. 您可以将重定向路径作为GET参数(例如redirectTo )传递到编辑页面,然后在完成编辑过程后将其重定向到该路径。

return new RedirectResponse($request->query->get('redirectTo');

You could make it more robust by checking whether or not that parameter is provided, and if it isn't, redirect to some sort of a default path. 您可以通过检查是否提供了该参数来使其更健壮,如果没有提供,则重定向到某种默认路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM