Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 37 ยท Views and Blocks

Views Contextual Filters, Relationships and Exposed Filters

Go beyond basic Drupal Views: exposed filters for visitors, contextual filters from the URL, relationships to related entities, aggregation and custom display handling.

A basic View shows the same list to everyone. Real sites need more: a search box on the events page, a page of events for this category, a list of articles with the author's name and photo. Drupal Views covers these needs with three features: exposed filters (visitor-controlled), contextual filters (driven by the URL or context) and relationships (joining related entities). This lesson explains each, then shows how they combine.

Start with Views Basics if building a simple View is still new to you.

Exposed filters

An exposed filter gives the visitor a form control. In the Views UI, add a filter and tick Expose this filter to visitors. You then configure:

  • Label and identifier (the query-string key, such as ?level=advanced).
  • Operator shown or fixed.
  • Required: whether a value must be chosen.
  • Allow multiple selections.
  • Remember the last selection (stored in the session).

Typical exposed filters: Title (contains), Category (select list), Level (radio buttons), Date range.

Under Advanced > Exposed form, choose whether to Use AJAX, show the form in a block, and set the Submit button text. Exposed filters make cached lists vary by query string; the cache system understands this through cache contexts (url.query_args).

Good UX: filters that are common go on top; "Reset" button; no filtering by internal values.

Contextual filters

A contextual filter (called "arguments" in older docs) filters by a value that is not typed by the visitor but supplied by context, most often the URL.

Example: a View with page path events/category/% has a contextual filter on the category term. Visiting /events/category/12 shows only events tagged with term 12.

You configure:

  • Which field: Content: Has taxonomy term ID.
  • When the filter value is NOT in the URL: display all results, show "Page not found" or hide the view.
  • When the filter value IS in the URL or a default is provided: "Provide default value" such as Content ID from URL (the node being viewed) or Current user ID.
  • Validation: ensure the argument is a real term and set a title from it ("Events in {{ arguments.tid }}").

Contextual filters shine in blocks: a "More from this author" block uses the author of the current node as its default value, so the same block works on every article.

Relationships

A relationship joins another entity so you can use its fields. Say your Article references an author (user) and you want to show the author's display name and picture. Add a relationship Content author, then add user fields; they now appear in the field list under the relationship.

Common relationships:

  • Content author (the user who wrote it).
  • Entity reference (the referenced taxonomy term, media or node).
  • Reverse reference (nodes that reference this one), e.g. "Speakers with their sessions".
  • Content revision and Taxonomy terms on node.

Relationships can be required (inner join: rows without the related entity disappear) or optional (left join: rows remain).

flowchart LR
    A["Article (base)"] -- "Relationship: author" --> U["User: name, picture"]
    A -- "Relationship: media reference" --> M["Media: image file"]
    A -- "Relationship: reverse reference" --> S["Session: title, room"]

Relationships expand the set of fields your View can use.

Aggregation and grouping

Under Advanced > Use aggregation, a View can group and count rows, for example "Number of articles per author". Aggregation changes how fields are queried (count, sum, average), so it needs care: switching it on affects every field. Another presentation tool is Grouping field: rows are grouped under headings, such as events grouped by month.

Other useful options

  • No results behavior: show a friendly "No events right now" message.
  • Header and footer: text, result summary ("Showing 1-10 of 42"), area with links.
  • Rewrite results: combine fields with Twig-like tokens: {{ field_date }} at {{ field_place }}.
  • Query settings: Distinct to remove duplicates when joins multiply rows.
  • Access: restrict who can see the View by permission or role.
  • Caching: set Tag based and let Drupal invalidate it automatically.

Reading a contextual filter in the configuration

Exported YAML for a contextual filter looks like this:

YAML
arguments:
  tid:
    id: tid
    table: taxonomy_index
    field: tid
    default_action: not found
    default_argument_type: fixed
    validate:
      type: 'entity:taxonomy_term'
    specify_validation: true

default_action: not found makes /events/category/ without an ID return a 404.

Exposed and contextual filters together

Both kinds can be active in the same View. This stand-in applies a contextual value (from the "URL") and exposed values (from the "form") to a data set, showing that they are just two sources of conditions.

JS Stand-in: exposed and contextual filters

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A relationship join

Here the stand-in joins articles to their authors the way a relationship does, with required and optional variants.

JS Stand-in: required versus optional relationships

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Performance cautions

Every relationship adds a join, and each field from it adds work. Keep relationships to those you need, limit rows, and prefer cached displays. Beware exposed filters on huge text fields and sorting by computed values; they may be slow. The Views UI preview includes a query log (enable it in Views settings) that shows the generated SQL, helpful when a View feels slow.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between an exposed filter and a contextual filter?

    Visitors control exposed filters through a form; contextual filters take values from context such as the path.
  2. 2. What does a relationship allow in Views?

    A relationship joins another entity so its fields can be displayed, filtered and sorted.
  3. 3. What happens with a required relationship when the related entity is missing?

    A required relationship is an inner join, so rows without a related entity disappear.
  4. 4. Which default value makes a 'more from this author' block work on every article?

    Contextual filters can default to values derived from the current page.

Summary

  • Exposed filters give visitors controls; contextual filters read values from the URL or other context.
  • Relationships join related entities so you can show their fields; required ones drop rows without a match.
  • Aggregation, grouping, no-results messages and rewriting refine output.
  • Watch performance: each relationship and filter has a cost.

Next: Blocks and Regions