Yii Framework Forum: JavaScript Pagination - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

JavaScript Pagination Rate Topic: -----

#1 User is offline   mindplay 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 397
  • Joined: 03-September 09
  • Location:New York

Posted 07 April 2010 - 09:51 AM

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.
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users