Views: Contextual filters

by Gisle Hannemyr

Contextual filters are a Views mechanism for dynamically refining the contents of a view. It might be helpful to think of them as "dynamic filters". This tutorial discusses the concept of context, and how to add contextual filters that comes with Drupal in the Views UI.

Table of contents

Drupal contributed extensions discussed in this chapter: Devel.

Introduction

One of the features of the Views is filters. It allows you to filter the view based upon some value.

Contextual filters extend this concept by allowing the value to be determined by context. A regular filter could be set up to give you all articles written by a specific user specified in the regular filter criterion. A contextual filter may be used to display all articles written by a user whose uid is passed in the path, written by the current user, written by the currently viewed user, or the same user who wrote the currently viewed node.

The filter values may be omitted, and then a default will be used. If not omitted, the filter values for a contextual filter are provided by the path. If a view has a base path /view/cfldemo, and two contextual filters for content type and author, the view page with the path starting with /view/cfldemo/article/2 will list all articles authored by the user with uid equal to 2..

Setting up

To be able to work through the examples in this tutorial, you need to set up your Drupal test site and install the necessary modules.

The Views project is in core. Enable the modules Views and Views UI.

If your site already has content, you may skip this step and work with that content instead. However, if you're testing this on a newly created test site, you can generate dummy content as follows:

Install the Devel project. Enable the Devel generate module. Create a test user (name it "test"). Navigate to Manage » Configuration » Development » Devel generate and generate 25 nodes each of types Article (machine-name: article) and Pasic page (machine-name: page). They will be randomly assigned to existing users.

What are contextual filters in Drupal?

For the sake of this tutorial, context is certain information that the view can access based on the page containing the view or the visitor interacting with the view.

For example, if a view has a block display which appears on all Drupal node pages, the view can make use of the current node context. In that case, almost any information about the current node we can use to dynamically change the results of our view. Similarly, a view could make use of the current user, and any information about the current user, as contextual input.

Like an exposed filters, a contextual filter is a mechanism in Views that we can use to create dynamic lists. The main difference between an exposed filter and a contextual filter is the source of the filter's value:

Create a View

The first step is just to create a basic view. Navigate to Manage » Structure » Views » + Add view. Name it "CFL Demo" (machine-readable name cfldemo) In "View settings" set it to show "Content" of type "Article". Leave the rest at the default.

views9_cfl01.png
Create view of Content of type Article.

Click on "Save and edit".

This launches the Views UI, where we can refine the View.

First, set the format to be a "Unformatted list" showing "Fields" of titles. By default, only the "Content: Title" field is shown. Just leave everyting else set to the defaults. The screen should look like this:

views9_cfl02.png
Use Views UI to configure the View.

So far this view only shows Content of type Article. To also show content of type Basic page, add this type to the filter criteria, then press "Add/Rearrange" to create a new filter group for the content types with an "Or" operator between the two content types. See screenshot below:

views9_cfl03.png
Modal to rearrange the filter criteria.

The change in operator will not happen until you press "Apply".

Add contextual filters

We can add contextual filter criteria to a view the same way we configure other settings in a view. Expand the "Advanced" section (third column), locate "Contextual filters".

views9_cfl04.png
Click "Add" to add a contextual filter.

Clicking on the button labeled "Add" will open a modal window that contains a list of available contextual filters we can add to our view.

In the modal, add The contextual filters "Authored by" and "Content type". They are both in the "Content" category.

views9_cfl05.png
Modal to add contextual filters.

Whern done, press "Add and configure contextual filters".

After adding contextual filters to the view, they must be configured. Due to the dynamic nature of contextual filters, this modal window contains a lot of options.

Let's go over these options and discuss how they might affect the view.

  1. When the filter value is not in the URL.
  2. When the filter value is in the URL or a default is provided.

The first section allows us to configure how the view should behave when a value for our Contextual Filter is not provided to the view. Another way of thinking about this is: "How do we want the view to act by default?"

views9_cfl06.png
Modal to add contextual filters.

It shows these radiobuttons:

Display all results for the specified field:
When selected, this option makes it so that the list of content is not filtered at all by this contextual filter.
Provide default value:
This option allows us to provide a default value to the contextual filter when no other value is provided.
Type:
Options for how to set the default contextual filter value. Often when configuring the default value for a contextual filter we're going to provide a specific fixed value, or we'll configure this option to look at the page URL for a default value.
Show "Page not found":
This option essentially makes the contextual filter value required. It makes sense to use this when the view has a path (like in a page display) and needs a value in the path in order to show specific results. A 404 "Page not found" error will display if there's no value provided.
Display a summary:
Rather than showing our list of content, the view will appear as a summary of possible values for the chosen contextual filter. There are configuration options available for the summary that allow us to chose the order of summary items shown, along with some simple formatting options.
Display contents of "No results found":
When selected, this option will cause the contents of the No Results Behavior section to appear when no contextual filter value is provided to the view.
Display "Access Denied":
Displays a 403 "Access Denied" error for the view when no contextual filter value is provided.

The second section allows us to configure how the view behaves when a value is provided, or there is a default. When a value is provided, it will automaticlly be used to filter results, you don't have to add it under "Filter criteria".

When a value is provided, we can validate the contextual filter value, or alter the title for the view. It shows these two checkboxes:

Override title:
This option allows us to dynamically change the Title for the view using the tokens available from the Replacement Patterns section.
Specify validation criteria:
With validation criteria we can configure the contextual filter to verify that the value provided meets certain expectations. Validating our filter values is a very useful and powerful option. We should use this option when possible.

If "Specify validation criteria" is checked, you get these additional settings:

Validator:
The mechanism by which we should validate our contextual filter value.
Action to take if filter value does not validate:
Configure how the view should act when a provided contextual filter value does not pass validation.

Configure the contextual filters

Now, provide values for both contextual filters.

The first modal is to configure "Content: Authored by".

Set the default behavior (i.e. when the filter value is not in the URL (path) be to use the user id from the currently logged in user. See the previous screenshot. We don't check anything for when the filter value is available or a default value is provided. When done, click "Apply and continue".

The second modal is to configure "Content: Content type".

Set the default behaviour use a fixed value. The value is the the machine-readable name for the Article content type (article). We don't check anything for when the filter value is available or a default value is provided.

views9_cfl07.png
Modal to add contextual filters.

When done, click "Apply". This was the last modal to configure the cotextual filters.

Finally, rearrange the contextual filters to determine their positions in the path. Click on the small down arrow in the menu for contextual filters (to the right of "Add"), and select "Rearrange". You rerrange by dragging and dropping the arrow-crosses to the left of the filter. We want "Content type" before Authored by".

views9_cfl08.png
Modal to add contextual filters.
views_cfl05.png.

Click "Apply" to save your new sequence.

Contextual filter values in the page path

Create a page display for the View by clicking on "+Add and selecting "Page" from the pulldown menu.

Provide a path for the menu. Click on the link to the right of "Path"under "Page settings" (second column) and type in "view/cfldemo". Click in "Apply"

noteThe official documentation tells you to by adding the percentage symbol (%) as a dynamic placeholder in the page path where we want the contextual filter value to appear. This does not always work. You may try not add this placeholder: See this Drupal.org support forum post for background.

The view has been configured to use two contextual filters: "Content: Content type" and "Content: Authored by", in that order.

Click "Save" in the Views UI to save the view.

Preview contextual filter values

When working on a view with contextual filters we can use the preview area to test that our filters are working as expected. At the top of the Preview section of the view edit form, there is a field labeled Preview with contextual filters. We can provide values to test our contextual filters using this field.

To test, reenter the View UI by pressing "Edit" for the View.

Now, when a user visits the path /view/cfldemo, she or he should see her/his own articles (because the that was the defaults picked when filters were missing from the URL). If we supply one or both filters, other lists are shown. Examples:

  • /view/cfldemo/page: Basic pages authored by the logged in user.
  • /view/cfldemo/page/1: Basic pages authored by user with uid 1.
  • /view/cfldemo/article/2: Articles authored by user with uid 2.

Final word

Like exposed filters, contextual filters are a mechanism in Views that we can use to create dynamic lists. The main difference between an exposed filter and a contextual filter is the source of the filter's value.

Here are links to miscellaneous materials about Contextual filters:


Last update: 2022-05-11 [gh].