问题
I'm using Slim framework for the first time, and so far everything is spot on. But there is one thing I can't seem to get my head around. After posting a form I would like to redirect back to the same page, but it uses a param in the url and I can't get back to it. This is what I have so far:
$app->post('/markets-:game', $authenticated(), function($game) use ($app) {
$request = $app->request();
$id = $request->post('game3');
$app->flash('global', 'game added');
$app->response->redirect($app->urlFor('games.markets', {"game:$id"}));
})->name('games.markets.post');
Any help would be much appreciated. Thanks
回答1:
urlFor method accepts two parameters:
- the name of the route;
- an associative array with all the parameters (optional).
Try this:
$app->response->redirect($app->urlFor('games.markets', array('game' => $id)));
回答2:
For anyone who lands here looking for a Slim 3 solution, the information is documented in the upgrade guide.
To redirect to a route with parameters is now as follows:
$url = $this->router->pathFor('games.markets', ['game' => $id]);
return $response->withStatus(302)->withHeader('Location', $url);
On another note, when naming routes you must now use
$app->get('/', function (Request $request, Response $response) {...})->setName('route.name');
Rather than the old ->name
Any other information regarding the differences from slim 2 to slim 3 can be found on the Slim Upgrade Guide
回答3:
Slim 3 Solution
The other answer for a Slim 3 solution is not very graceful and also misses the fact that an empty array must be passed as a second parameter to pass the query parameters as a third parameter; without this, no query parameters are used.
Therefore, the answer for Slim 3 would simply be the following.
return $response->withRedirect($this->router->pathFor('named.path.of.route', [], [
'key1' => $value1,
'key2' => $value2
]));
来源:https://stackoverflow.com/questions/30970089/slim-framework-redirect-with-params