Showing X-Y of N results
On a view that stretches across multiple pages, it's polite to let your users know how many items you're displaying and what the total number is. This is not something that the pager system does by itself. Luckily, all of the relevant information is available through various global variables.
Potentially the most useful global for working in your view's header or footer is $current_view. This global basically outlines all the config settings for your view, such as the filters, column headings and - most relevant here - the number of items to display per page. (This is a global that all views coders should be made aware of, since otherwise this information simply isn't available to you in these code fields.) Unfortunately, $current_view doesn't actually tell you what page you're on. To get this information we have to delve into the pager globals.
The Pager system creates three global variables relevant to this task: $pager_page_array, $pager_total_items and $pager_total. All three of these are built as arrays to cope with the scenario where there's more than one pager on the page (they are, after all, global). There's rarely more than one pager on a page, so for the most part the key you're looking for will be 0. This article is not an in-depth discussion of the pager system, though, so you're going to have to take my word on it that you get the current page by reading $pager_page_array[0].
Let's see that in action!
<?php
// Lift the globals into local scope
global $pager_page_array, $pager_total_items, $pager_total, $current_view;
if ($pager_total[0] == 1) { // Number of pages == 1
echo 'Showing <b>' . $pager_total_items[0] . '</b> results';
}else{
// Page number is zero-based (first page is 0)
// Multiply pager_limit by page number (eg 0, 15, 30) and add 1 to get first item
$start = 1 + ($pager_page_array[0] * $current_view->pager_limit);
// Multiply pager_limit by page number + 1 (eg 15, 30, 45) to get last item
$end = (1 + $pager_page_array[0]) * $current_view->pager_limit;
// Use total items count if this is less than that
if ($end > $pager_total_items[0]) $end = $pager_total_items[0];
echo "Showing $start-$end of <b>" . $pager_total_items[0] . '</b> results';
}
?>As an endnote, best practise would be to turn each of those echoed outputs into translatable strings using t() - for example:
<?php
echo t('Showing <b>!total</b> results', array('!total' => $pager_total_items[0]));
?>-- Code originally developed in the Module Development forum.
