I needed a variation of CPagination that would allow me to generate javascript:-links instead of URLs.
Here’s what I came up with:
<?php
/**
* A pagination class that generates JavaScript calls instead of URLs.
*/
class CJSPagination extends CPagination
{
/**
* @var string JavaScript function-call template
*
* {url} will be replaced by the controller/action URL (without parameters)
* {page} (or whatever name you've chosen with $pageVar) will be replaced by the page-number
* {params} will be replaced by a JSON object with all parameter values
*
* Individual parameters (from $params, or $_GET if no $params are set) can be access using tokens, too.
*
* Example Templates:
*
* load_page({page}) => load_page(3)
*
* load_{tabName}({page}) => load_stuff(7)
*
* $.get('{url}', {params}) => $.get('/controller/action', {page:4, param:'value'})
*/
public $template="$.get('{url}', {params})";
/**
* Creates the JavaScript link for pagination, using the current $template.
*/
public function createPageUrl($controller,$page)
{
$params = $this->params===null ? $_GET : $this->params;
if ($page>0) // page 0 is the default
$params[$this->pageVar] = $page+1;
else
unset($params[$this->pageVar]);
$url = $controller->createUrl($this->route);
foreach ($params as $name=>$value)
$$name = CJSON::encode($value);
$params = count($params) ? CJSON::encode($params) : 'null';
return 'javascript:' . preg_replace("/\{([^\{]{1,100}?)\}/e", "$$1", $this->template);
}
}
By creating a template for the JavaScript call (see examples above), I can now put pagers in search results that are loaded via AJAX.
I’ve only tested this with CLinkPager, but in theory, this should work with any kind of CPager.
I invite you to adopt this class for inclusion in Zii (or Yii) if you’d like.