首页 > 解决方案 > Symfony 4,登录(或注销)后如何将用户重定向到上一页?

问题描述

例如,用户转到“关于我”页面。从这个页面,他可以通过导航栏中的按钮登录或注销。

当用户登录或注销时,他会自动重定向到主页。相反,我想将用户重定向到上一页(本例中的“关于我”)

阅读文档后,我找不到/不了解如何为我的目的配置重定向

有人可以解释/给我看:?谢谢你 !

标签: symfony4

解决方案



我也遇到过这个问题。
我假设你使用 ```Symfony4.4``` 并使用 ```make:auth``` 来创建登录界面。在你的 ``SecurityController```(你有登录路径的那个)中,你使用 ```$request->headers->get('referer')``` 将你来自的 URL 传递给树枝登录页面。
public function login(AuthenticationUtils $authenticationUtils, Request $request): Response
    {
        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();
        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();
        return $this->render('security/login.html.twig', [
            'last_username' => $lastUsername,
            'error' => $error,
            'back_to_your_page' => $request->headers->get('referer')
        ]);
    }

然后在 Twig 页面 (login.html.twig) 中使用back_to_your_page登录表单中的变量。_target_path变量在这里是必不可少的。

<form>
...
<input type="hidden" name="_target_path" value="{{ back_to_your_page }}"/>
...
</form>

现在是最后一部分。在onAuthenticationSuccess函数所在的 LoginFormAuthenticator (make:auth) 中,您使用该_target_path变量。

public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        return new RedirectResponse($request->get('_target_path'));
    }

测试和享受。我知道这是一个迟到的回应,但也许其他人将来会得到帮助。


推荐阅读