Selectable Items per Page Hack for Drupal 6 Views

I’m sure regular contributors to Drupal will cringe at what I’m about to show you, but I found it to be a handy trick. Let’s say you’re using the Views module in Drupal 6 and you want a way to dynamically control the number of items listed in a view. In my case, a client I was working for wanted to be able to select the number of products displayed per page.

Reasonable request, right? Unfortunately, Views doesn’t handle it out of the box. After a bit of fiddling, I managed to come up with the following hack. Mind you, I use the term “hack” here literally; you should never edit a module like this if you can avoid it, if only because it makes updates painful later on.

The operative code is in the pre_execute() function on line 1795 of modules/plugins/views_plugin_display.inc. It normally looks like this:

$this->view->set_items_per_page($this->get_option('items_per_page'));

As the name suggests, anything you feed to this function will set the number of items displayed by the view. In my case, I wanted to use a URL variable coupled with a drop-down menu and some jQuery to toggle it, so I changed it like so:

$this->view->set_items_per_page((($_GET['items-per-page'] > 0) ? $_GET['items-per-page'] : $this->get_option('items_per_page')));

Voila! One line of code and you’re off to the races. Type ‘?items-per-page=X’ into the URL (with X being a number, of course) and it should work like a charm. The pagination even follows suit.

For those who want the full solution, here’s the code for the drop-down menu. You’ll need to add it to a view-specific template file. Just follow the pattern to create your own items per page options.

<?php $items_per_page_override = ($_GET['items-per-page'] > 0) ? $_GET['items-per-page'] : 12; ?>
<div id="items-per-page-selector"><strong>Items per Page:</strong> <select>
<option value="12"<?php echo ($items_per_page_override == 12) ? ' selected="selected"' : ''; ?>>12</option>
<option value="18"<?php echo ($items_per_page_override == 18) ? ' selected="selected"' : ''; ?>>18</option>
<option value="24"<?php echo ($items_per_page_override == 24) ? ' selected="selected"' : ''; ?>>24</option>
<option value="9999"<?php echo ($items_per_page_override == 9999) ? ' selected="selected"' : ''; ?>>All</option>
</select>

And here is the jQuery that controls the behavior of the drop-down menu.

$(document).ready(function(){
$('#items-per-page-selector select').change(function(){
window.location = '?items-per-page=' + $(this).val();
});
});

Comments

One Response to “Selectable Items per Page Hack for Drupal 6 Views”

  1. bronius on March 1st, 2010 4:28 pm

    Note: I think it’s possible to override this value without a .module hack, at least in the case of embedded views. In the case of embedded views, I believe you could simply set $view->set_items_per_page just like you did in your hack but in the embed.

Share Your Thoughts