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

时间:2016-11-17 13:29:38

标签: php slim slim-3

我正在尝试将用户重定向到包含错误和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]));

1 个答案:

答案 0 :(得分:1)

您已经使用过slim/flash,但之后您就这样做了:

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

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

后要使用的数据
  

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

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

来源(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');