Drupal Paging



Drupal has very powerful paging capabilities. This document explains it usage and capabilities using examples. Lets start by creating a module called paggar. If you are wondering why I used such strange sounding name for the modules, her goes a simple explanation. pager module already exists and pagger is not a very polite word.

paggar.info

name = paggar
description = paging example
package = mole
core = 6.x
version = 6.3
project = mole

paggar.module

// paggar.module - molecularsciences.org

// help
function paggar_help($section) 
{
  switch ($section) {
    case 'admin/modules#description':
      return t('Paging Example');
  }
}

// permissions
function paggar_perm()
{
	return array('enable paggar');
}

function paggar_menu()
{
	$items['paggar'] = array(
		'title' => 'Paging example',
		'page callback' => 'paggar_example',
		'access callback' => 'user_access',
		'access arguments' => array('enable paggar'),
		'type' => MENU_CALLBACK
	);
	return $items;
}

// paging example
function paggar_example()
{
	// title for the page
	drupal_set_title("Paging example");

        // query
	$q = "select distinct title from {node} where type like 'page'";

	$rs = db_query($q);
	$o = '<ul>';
	while($rw = db_fetch_object($rs))
	{
		$o .= '<li>' . $rw->title . '</li>';
	}
	$o .= '</ul>';
	
        return $o;
}

This module would print the titles of all page nodes. No paging yet. To add paging, we need to provide the following:

  • define how many nodes to print per page
  • specify a count query e.g. select count(*) from ...
  • use pager_query() instead of db_query()
  • use pager_theme() to print paging links
// paging example
function paggar_example()
{
	// title for the page
	drupal_set_title("Paging example");

	// how many nodes per page
	$nodes_per_page = 20; 

        // query
	$q = "select distinct title from {node} where type like 'page'";

	// count query
	$cq = "select count(distinct title) from {node} where type like 'page'";

	$rs = pager_query($q,$nodes_per_page,0,$cq);

	$o = '<ul>';
	while($rw = db_fetch_object($rs))
	{
		$o .= '<li>' . $rw->title . '</li>';
	}
	$o .= '</ul>';

        // print paging links
	$o .= theme('pager', NULL, 10);

	return $o;
}

You must pass the query, an integer specifying the number of entries to display per page, paging identifier, and the count query to the pager_query