如何在重定向之后重定向和存储请求的数据

人气:595 发布:2022-10-16 标签: php slim slim-3

问题描述

我正在尝试将用户重定向到登录页,但出现错误和闪烁消息。

目前我正在执行以下操作:

return $this->container->view->render($response,'admin/partials/login.twig',['errorss'=>$errors]);

但我想重定向到登录页面,同时仍然有错误消息和闪烁消息。我尝试了这种方法,但不起作用:

$this->container->flash->addMessage('fail',"Please preview the errors and login again."); 
return $response->withRedirect($this->container->router->pathFor('admin.login',['errors'=>$errors]));

推荐答案

您已经使用了slim/flash,但随后您执行了以下操作:

return $response->withRedirect($this->container->router->pathFor('admin.login',['errors'=>$errors]));

这是不正确的。Router#pathFor()方法上的第二个参数不是用于重定向后使用的数据

路由器的pathFor()方法接受两个参数:

路由名称 路由模式占位符和替换值的关联数组

来源(http://www.slimframework.com/docs/objects/router.html)

因此您可以使用第二个参数设置类似profile/{name}的占位符。

现在您需要将所有错误添加到slim/flash`中。

我在修改后的Usage Guide of slim/flash

上解释了这一点
// can be 'get', 'post' or any other method
$app->get('/foo', function ($req, $res, $args) {
    // do something to get errors
    $errors = ['first error', 'second error'];

    // store messages for next request
    foreach($errors as $error) {
        $this->flash->addMessage('error', $error);
    }

    // Redirect
    return $res->withStatus(302)->withHeader('Location', $this->router->pathFor('bar'));
});

$app->get('/bar', function ($request, $response, $args) {
    // Get flash messages from previous request
    $errors = $this->flash->getMessage('error');

    // $errors is now ['first error', 'second error']

    // render view
    $this->view->render($response, 'admin/partials/login.twig', ['errors' => $errors]);
})->setName('bar');

959