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

断了今生、忘了曾经 提交于 2019-12-12 02:46:14

问题


I am trying to redirect the user to the login page with errors and a flash message.

Currently I'm doing this:

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

But I want to redirect to the login page, while still having the errror messages and the flash message. I tried this way but does not work:

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

回答1:


You've already used slim/flash, but then you did this:

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

which is not correct. The second parameter on the Router#pathFor() method is not for data to use after the redirect

The router’s pathFor() method accepts two arguments:

  1. The route name
  2. Associative array of route pattern placeholders and replacement values

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

So you can set placeholders like profile/{name} with the second parameter.

Now you need to add your errors all together to the slim/flash`.

I'm expaining this on the modified 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');


来源:https://stackoverflow.com/questions/40656208/how-to-redirect-and-store-data-for-the-request-after-the-redirect

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!