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


How to redirect and store data for the request after the redirect

我试图将用户重定向到带有错误和flash消息的登录页面。

当前我正在做这个:

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

但是我想重定向到登录页面,同时仍然有错误消息和flash消息。我试过这种方式,但不工作:

$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()方法接受两个参数:

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

<一口>源(http://www.slimframework.com/docs/objects/router.html)

所以你可以用第二个参数设置像profile/{name}这样的占位符。

现在您需要将您的错误全部添加到slim/flash '。

我在修改后的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');