Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Symfony helper for getting the current action URL and changing one or more of the query parameters?

Tags:

php

symfony1

What I'd like to do is take the route for the current action along with any and all of the route and query string parameters, and change a single query string parameter to something else. If the parameter is set in the current request, I'd like it replaced. If not, I'd like it added. Is there a helper for something like this, or do I need to write my own?

Thanks!

[edit:] Man, I was unclear on what I actually want to do. I want to generate the URL for "this page", but change one of the variables. Imagine the page I'm on is a search results page that says "no results, but try one of these", followed by a bunch of links. The links would contain all the search parameters, except the one I would change per-link.

like image 288
Rytmis Avatar asked Jan 04 '10 22:01

Rytmis


3 Answers

Edit:

Ok I got a better idea now what you want. I don't know whether it is the best way but you could try this (in the view):

url_for('foo', 
        array_merge($sf_request->getParameterHolder()->getAll(), 
                    array('bar' => 'barz'))
)

If you use this very often I suggest to create your own helper that works like a wrapper for url_for.

Or if you only want a subset of the request parameters, do this:

url_for('foo', 
         array_merge($sf_request->extractParameters(array('parameter1', 'parameter3')),
                     array('bar' => 'barz'))
)

(I formated the code this way for better readability)


Original Answer:

I don't know where you want to change a parameter (in the controller?), but if you have access to the current sfRequest object, this should do it:

$request->setParameter('key', 'value')

You can obtain the request object by either defining your action this way:

public function executeIndex($request) {
     // ...
}

or this

public function executeIndex() {
     $request = $this->getRequest();
}
like image 66
Felix Kling Avatar answered Oct 27 '22 00:10

Felix Kling


For symfony 1.4 I used:

$current_uri = sfContext::getInstance()->getRouting()->getCurrentInternalUri();
$uri_params = $sf_request->getParameterHolder()->getAll();
$url = url_for($current_uri.'?'.http_build_query(array_merge($uri_params, array('page' => $page))));
echo link_to($page, $url);
like image 28
Erq Avatar answered Oct 27 '22 00:10

Erq


Felix's suggestion is good, however, it'd require you to hard core the "current route"..

You can get the name of the current route by using:

sfRouting::getInstance()->getCurrentRouteName()

and you can plug that directly in url_for, like so:

url_for(sfRouting::getInstance()->getCurrentRouteName(), 
         array_merge($sf_request->extractParameters(array('parameter1', 'parameter3')),
                     array('bar' => 'barz'))
)

Hope that helps.

like image 20
0x6A75616E Avatar answered Oct 26 '22 23:10

0x6A75616E