Warning message

Documentation is currently being migrated into the new system. Some pages might be temporarily missing, and some guides might appear empty. Thank you for your patience while we are improving Drupal.org documentation.

Paging non-SQL data

Last updated on
24 September 2016

Generic Array Pager (D6)

With the following function, you can use the Drupal core pager with any array with only two lines of code.


/** 
 * A generic array pager for Drupal. 
 * For Drupal 5 and 6, the default limit is 10. For Drupal 7 it is 9. 
 */
function pager_array_splice($data, $limit = 9, $element = 0) {
  global $pager_page_array, $pager_total, $pager_total_items; $page = isset($_GET['page']) ? $_GET['page'] : '';
  // Convert comma-separated $page to an array, used by other functions.
  $pager_page_array = explode(',', $page);
  // We calculate the total of pages as ceil(items / limit). 
  $pager_total_items[$element] = count($data);
  $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
  $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element], ((int)$pager_total[$element]) - 1));
  return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
} 

The usage is as simple as:


$output = ''; $tree = taxonomy_get_tree($vocab->vid); $tree = pager_array_splice($tree, 5); // Do something with the 5 terms $output .= theme('pager', array('quantity' => 5)); 

SOAP example (D7)


This is the function that gets XML data.

We use a function from http://php.net/manual/es/book.simplexml.php to transform XML data into an array.

The pager is initialize thru pager_default_initialize() function.

The pager is added using Drupal standard theme pager.

function page_soap_arguments() {
  $sx = simpleXMLToArray(simplexml_load_file('http://www.example.com'));
		
  // Gets number of records
  $total = count($sx);
  // Define items per page for paging
  $num_per_page = 10;
		
  // Initialize pager and gets current page
  $current_page = pager_default_initialize($total, $num_per_page);

  // Split the items up into chunks:
  $chunks = array_chunk($sx, $num_per_page);
  // Get the items for our current page:
  $current_page_items = $chunks[$current_page];
  // Theme each item. Note that the theme
  // some_theme_hook is left out of this tutorial
  // for simplicity
  foreach($current_page_items as $i => $item) {
    $current_page_items[$i] = array(
      '#theme' => 'some_theme_hook',
      '#item' => $item,
    );
  }

  // Generate the render array for our page
  $render_array['page'] => array (
    '#theme' => 'item_list',
    '#items' => $current_page_items,
  );
  // Calls Drupal standard pager theme and set 5 page links on pager
  $render_array['pager'] = array (
    '#theme' => 'pager',
    '#quantity' => 5,
  );

  return $render_array;
}