Drupal

Using Drupal Contextual Filters in Views

It can take a while when you're new, but once you start to wrap your head around Views, that is when Drupal gets really fun. In this tutorial, I'll go over how to use Contextual Filters in Views to alter your content dynamically based on information in the URL. If you're a visual learner, you can skip to the video at the end of this post for a detailed walk through of the process.


Filed under:

This article is one of Metal Toad's Top 20 Drupal Tips. Enjoy!

It can take a while when you're new, but once you start to wrap your head around Views, that is when Drupal gets really fun. In this tutorial, I'll go over how to use Contextual Filters in Views to alter your content dynamically based on information in the URL. If you're a visual learner, you can skip to the video at the end of this post for a detailed walk through of the process.

Kittens vs Specific Kittens

In this example, have page of cat photos. It's made with a standard view that pulls from content type 'Animals' and then narrows it down with a standard filter based on a Species taxonomy list.

A page of kittens

Drupal Contextual Filters allows us to filter content based on dynamic information. It doesn't always have to come from the URL, but that is the most common example. Here's how you do it.

Standard view with normal filters

In the Advanced tab of your view, click 'add' next to Contextual filters. I want to filter on the name of the animal, so I do a search to narrow down the choices and then choose the name field.

Adding the name filter

Now you have some options, the two most important being:

  1. What to do when your filter is not in the URL
  2. What to do when your filter is in the URL

In the first case, I've chosen to just display all the results as normal. In the second case, I've overridden the title of the view and replaced the Previous title 'Kittens' with the actual name of the animal by using the placeholder '%1' which tells Drupal to take the first filter (previously known as 'arguments') in the URL and use it as the title as well. Using '%2' would take the second argument (if there is one) and so on.

Set your filter options

You can test your filter by typing it into the preview window and hitting 'Update Preview'.

Enter your filter into the preview field

If your results narrow to your satisfaction, save the view, then try it out on the page. We should be able to go to sandbox/kittens/[name] and have just one pet show up. Kinda like this:

The final product

Isn't Xander cute?

Pat yourself on the back and have a celebratory cupcake. You're one step closer to Views mastery in Drupal.

Similar posts

Get notified on new marketing insights

Be the first to know about new B2B SaaS Marketing insights to build or refine your marketing function with the tools and knowledge of today’s industry.