在 Symfony2 中,如何刷新页面,只更改 GET 字符串的一个参数


如何

刷新页面,更改GET字符串的一个参数?

假设我在此页面上:

/my/page?foo=bar&asd=qwe

在控制器中,我有这个变量:

$var = array('foo' => 'woof');

如何使用该变量重定向到此页面?

/my/page?foo=woof&asd=qwe

或者,如果我在此页面上:

/my/page

使用该变量,如何访问此页面?

/my/page?foo=woof

如果我理解得很好,你想做的是以下几点:

public function myAction()
{
    $request = $this->getRequest();
    $params = $request->query->all();  // get the original GET parameters
    $var = array('foo' => 'woof');
    $newParams = array_replace($params, $var); // only replaces the 'foo' parameter, keeping the rest as is
    $url = '/my/page?'.http_build_query($newParams); // you can also use $this->generateUrl() if you use routing (which would be a good idea)
    return $this->redirect($url);
}
public function onKernelRequest(GetResponseEvent $event) {
    $request = $event -> getRequest();
    $routes = $this -> router -> getRouteCollection();
    $routeName = $request -> get("_route");
    $params = $request -> query -> all();
    $route = $routes -> get($routeName);
    preg_match_all("/{(.+)}/", $route -> getPattern(), $routeParams);
    $routeParams = $routeParams[1];
    foreach ($routeParams as $key => $value) {
        $params[$value] = $request -> get($value);
    }
    if (array_key_exists("to_remove", $params)) {
        unset($params['to_remove']);
        $url = $this -> router -> generate($routeName, $params);
        $event -> setResponse(new RedirectResponse($url));
    }
}

最新更新