CakePHP: Select Box Pagination

by dom111 on August 27th, 2009

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:

<!-- Items per page: -->
<select onchange="setURL('limit', this.value)">
  <option value="10"<?=($params['named']['limit'] == '10') ? ' selected="selected"' : ''?>>10</option>
  <option value="20"<?=($params['named']['limit'] == '20') ? ' selected="selected"' : ''?>>20</option>
  <option value="50"<?=($params['named']['limit'] == '50') ? ' selected="selected"' : ''?>>50</option>
  <option value="100"<?=($params['named']['limit'] == '100') ? ' selected="selected"' : ''?>>100</option>
</select>
 
<!-- Page: -->
<select onchange="setURL('page', this.value)">
<?php for ($i = 1; $i <= $paginator->counter(array('format' => '%pages%')); $i++): ?>
  <option value="<?=$i?>"<?=($params['named']['page'] == $i) ? ' selected="selected"' : ''?>><?=$i?></option>
<?php endfor ?>
</select>

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!

From CakePHP, Coding, PHP

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS