Saturday, March 20, 2010

ReBuild Pagination for Controller on CodeIgniter

this function is using for easily using pagination library in one line.
just insert this function in your controller, and the other function call it:

/**
 * set paging for easy use :)
 * @access private
 * @param string $url
 * @param int $total
 * @param int $perpage
 * @param int $numlink
 * @return void
 */
function setPaging($url='', $total=0, $perpage=20, $numlink=3){
 if(!is_numeric($total)){
  $total=0;
 }
 if(!is_numeric($perpage)){
  $perpage=20;
 }
 if(!is_numeric($numlink)){
  $numlink=3;
 }
 $this->load->library('pagination');
 $segment=explode('/',$url);


 $config=array(
  'base_url' => site_url($url),
  'uri_segment' => count($segment)+1,
  'total_rows' => $total,
  'per_page' => $perpage,
  'num_links' => $numlink,
  'first_link' => "«",
  'last_link' => "»",
  'prev_link' => "<",
  'next_link' => ">",
 );
 $this->pagination->initialize($config);
 $this->data['paging'] =$this->pagination->create_links();
 $this->data['limit'] =$config['per_page'];
 $this->data['start'] =$config['per_page'] *($this->pagination->cur_page -1);
 if($this->data['start']<0){
  $this->data['start'] =0;
 }
}


make sure this function is in your controller class.

and just call in your other function in the same controller
example:

$this->setPaging('article/page', $total_rows, $limit);


and now in your view, you not need to check your pagination
ex:

<?php echo $paging;?>

or you wana make sure? use this:

<?php
if(isset($paging)){
 echo $paging;
}
?>


and this is your starting number for your list on this page:

<?php $i=isset($start)?$start:0;?>


and this is your limit number for your list on this page:

<?php $x=isset($limit)?$limit:20;?>

No comments:

Post a Comment