How to: use GET parameters in Drupal Views conditional filters

Posted By Brad Czerniak on Wednesday, June 4, 2014 - 17:54

It's kind of a bummer: Views exposed filters use GET parameters to pass arguments, but Views conditional filters use core path arguments.

Sometimes you want to use the exposed filter values for different displays, or swipe GET parameters from non-View functionality.

Example

On the Galaxie site, we have a View with exposed filters where you can toggle by a particular machinery category. Each page that comes up then has a block that describes the category you're viewing.

That block is a view with a conditional filter that gets the category from a GET parameter in the URL.

How

There are a few bad ways to do this, which I've uneasily played with on other projects:

  • Use "Provide Default Value", but select "PHP Code" and get the argument that way
  • Change the value in one of the Views build-execute-render hooks

Both of these options aren't reusable, and the first ends up with code in the database. Clearly there has to be a better way.

The get_arguments module is the natural result. It adds a new option to the "Provide default value" dropdown that lets you specify a GET parameter to use for the value you wish to filter from.

Technical detail

It's a very simple module. The .module file just tells Views that it uses the API. The .views.inc calls hook_views_plugins() and defines an "argument default" plugin. Then there's just a class with three small methods:

  1. option_definition: tell Views that there's a configuration form field
  2. options_form: build a form item for the option that was defined
  3. get_argument: Take the passed data and return either the value or FALSE

That's all it takes.

Why I love it

Segmenting content into blocks makes site-building much easier. If the client wants to move that block to the bottom of the page, it's drag-and-drop easy. It removes the need for dirty-feeling modules like views_field_view, too.

With smart use of conditional filters and block display settings, you can configure site content to display exactly where you want it while ensuring good performance. And often it doesn't even require the fanciness of context or panels or anything else besides core.

Looking for sites built the Drupal way? Contact us.

10 step drupal security audit guide