Drupal 7: Programatically Create Pagination with Example

The function theme() will help to create pagination programmatically in Drupal. While passing the argument "pager" to a theme() with the additional parameter for construct pager will return the pager. The below syntax and example demonstrate how to implement pager in Drupal 7.

Syntax:
PAGER_COUNT: Number of
ATTRIBUTES: Additional attributes for the pager given as array. Ex: Class, Id,.

$output = theme('pager', array('quantity', PAGER_COUNT, 'attributes' => ATTRIBUTES));

Example:

$result = db_query("SELECT n.nid, n.title FROM {node} ORDER BY n.nid ASC");
$rows = array();
foreach($result as $key => $row) {
  $rows[] = array('nid' => $row->nid, 'title' => $row->title);
}
if (count($rows)) {
  $header = array('nid' => 'Node ID', 'title' => 'Title',); // Constructing header.
  $perPage = 20;
  $currentPager = pager_default_initialize(count($rows), $per_page); // Initializing pager.
  $chunks = array_chunk($rows, $perPage, TRUE); // Split all records in to chunked.
  $output = theme('table', array('header' => $header, 'rows' => $chunks[$currentPager], 'attributes' => array('class' => 'node-list', 'id' => 'node_list'));
  $output .= theme('pager', array('quantity',count($rows), 'attributes' => array('class' => 'node-pager', 'id' => 'node_pager'),));
  print render($output);
}

 

Category: