blog-banner

Creating Pager in Drupal (without db_select() and PagerDefault)

  • Drupal 7
  • Drupal Planet
  • Pager

DB_Select in Drupal 7

 

Pager: no new to the dictionary of Web, plays an important role in reducing long scrolling and improvises the visual look of the site. One of the pages on my site lists statistics-based details. It wasn't that appealing to go ahead with this page which had almost 100 plus items to display. At this point, I had a sudden idea to split the statistics with the help of a pager.

I am stoked with this decision as I thought PagerDefault in Drupal can help me a hand. But later I recognized the same cannot be used in my case as it was not rendered with any query. What I had on my page was just an array which was rendered by a theme_table(), to construct a pager for this proved my decision quite rugged. I leave no stones unturned to pick the best way to solve my need.

And finally, I found a solution and created a pager. The below-mentioned code proved worthy of a solution.,

  1. $per_page = 10;
  2. // Initialize the pager
  3. $current_page = pager_default_initialize(count($rows), $per_page);
  4. // Split your list into page sized chunks
  5. $chunks = array_chunk($rows, $per_page, TRUE);
  6. // Show the appropriate items from the list
  7. $output = theme('table', array('header' => $header, 'rows' => $chunks[$current_page]));
  8. // Show the pager
  9. $output .= theme('pager', array('quantity',count($rows)));

The Page_default_initialize() as mentioned initializes pager for a page. The first argument in my case was the total number of items that were to be paged. I broke this total item into an array of size 10 using array_chunk(). And the rest is just a normal table-theming.

The above function can be used in the corresponding theme function either at the module level or at the template level. Once done the pager must start working in your case too.

Get awesome tech content in your inbox