chacadwa.com

Technical blog and writings by Micah Webner.

Drupal 7 Display array contents with pager

This example shows how to generate a render array from an array of data that includes a pager. This example will theme the content as an item_list, but the content section could be parsed and rendered as a table or by any other means, depending on the content of the $rows array.

The trick to using theme_pager(), as I discovered, is that (under normal circumstances and typical usage) it gets all of its information from pager_default_initialize(). The output selection is handled by the PHP array_slice() function.

/**
 * Page callback for some paged data.
 */

function mysite_some_paged_data() {
  $output = NULL;
  $rows = mysite_generate_a_big_array();
  if (!empty($rows)) {
    $limit = 20;
    $page = pager_default_initialize(count($rows), $limit, 0);
    $offset = $limit * $page;
    $output = array(
      array(
        '#theme' => 'item_list',
        '#items' => array_slice($rows, $offset, $limit),
      ),
      array(
        '#theme' => 'pager',
      ),
    );
  }
}
Topics: