tags:

views:

1029

answers:

2

Hi,

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.

+1  A: 

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();
}
Felix Kling
Preferably, I'd like to do it in the view, using something like url_for('foo', array('bar' => 'baz')), but so that the current variables are maintained and I don't have to explicitly set them.
Rytmis
If i recall i believe the request is exposed as `$sf_request` in the view.
prodigitalson
+1  A: 

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:

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.

JuanD
I was so focused on the parameter merging thing that I totally forgot about the current page. Good point. You should reformat your code though.
Felix Kling
Actually, I only need this in one place for now, so hard-coding the route name is not a problem. I had already come up with basically the same solution, although I didn't know about the parameter holder. Thanks to both of you for your great suggestions. :)
Rytmis