Using CakePHP’s built in pagination system has saved me so much time in my current day job, but the latest designs I’m working on have drop-down box style pagination, as it’s possible to get many pages of results.
To change the named parameters in the current URL I’ve created this small javascript function that will amend the URL:
/**
* setURL
*
* Modifies the current URL and redirects the browser
*
* @param string key The name of the parameter to set
* @param mixed value The value to set the parameter to
* @return void
* @author Dom Hastings
*/
function setURL(key, value) {
// set up the url separators
var separator = {
// site.url/controller/action/key1:value1/key2:value2
'key': '/',
'value': ':'
}
// get the current url
var url = window.location.href;
// check if the specified key already exists
var exists = url.indexOf(separator.key + key + separator.value);
// if it does
if (exists > -1) {
// find the next separator.key
var last = url.indexOf(separator.key, exists + 1);
// if there is one
if (last > -1) {
// replcae the existing value with the one passed
url = url.substr(0, exists) + separator.key + key + separator.value + escape(value) + url.substr(last);
// if not
} else {
// just append it
url = url.substr(0, exists) + separator.key + key + separator.value + escape(value);
}
// if it's not already in there
} else {
// if the URL doesn't end with a separator.key
if (url.substr(-1) != separator.key) {
// append it
url += separator.key;
}
// append the value
url += key + separator.value + escape(value);
}
// set the url
window.location.href = url;
}
Coupled with the following code to my view:
Hopefully it’ll help anyone else deal with a similar problem!
Note: If there’s a simpler, more accessible way to do it, I’d really like to know!
Nice! Thanks for this!
What happen if for example the action isn’t set, for example the action index is called for default when you call a controller.
You must to write something like url = url+”/index”; before if (url.substr(-1) != separator.key) in the javascript function.
But it only will works if the paginator is in the index…
Hey there!
So this was made quite a long time ago and I don’t know if it’s still particularly relevant (I haven’t worked on CakePHP much at all for the past eighteen months!), but I guess you could expose your default action to JavaScript somehow if you needed to work around it? This fix was originally for a very specific function, so it’s not very forgiving in situations like the one you mention…
Hope this article was able to point you in a useful direction though!
Thanks,
Dom