0

我正在尝试将用户重定向到登录页面,并显示错误和一条消息。

目前我正在这样做:

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]));
4

1 回答 1

1

您已经使用过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');
于 2016-11-18T17:06:35.377 回答