Apprenez Drupal

Sélecteur de langue

Qu’est-ce qu’une vue dans Drupal? Comment fonctionnent-ils?

In Drupal, a view is a listing of information. It can a list of nodes, users, comments, taxonomy terms, files, etc. A view scans your website using any criteria you specify and presents the results in the format of your choice. Example formats include a HTML table, a RSS feed, a PDF document, a CSV document, an interactive map, an image slideshow, or a JSON representation to be used as a REST endpoint. The same content can be presented in multiple formats at the same time. For instance, you can present a table of user information and on the same page a link to download the data in CSV format.

Let’s continue our journey to understand more Drupal concepts. As you might have already noticed, they build on each other. Today, you will learn how nodescontent types, and fields can be used as part of views configurations. Also, you will find examples of blocks that are created using views.

Understanding Views terminology

There are three key terms that you need to be aware of: the Views module, the Views UI module, and a view instance. The Views module is the engine of the whole system. Often described as a SQL query builder, it allows you to fetch data stored in Drupal’s database, assemble a list of results, and present them in various output format. One of the great benefits it provides is that site builders do not need to know SQL or details about the underlying database structure. Having a basic understanding of Drupal concepts like nodes, content types, and fields suffices in most cases. Using the Views UI module it is possible to create view instances which encapsulate the configuration of what elements to display and how.

The Views UI module is the visual user interface of the system. It offers a setup wizard that guides you through the process of creating and configuring a view. Once all the views for a site have been created, the Views UI module can be uninstalled and the individual view instances will continue working. For one, you gain a bit of performance as there is less code to execute on page loads. But more importantly, editors will not be able to modify the views configuration using the administration interface in production environments. Site builders will be able to continue making changes in development environments as needed. Then, they can push the changes as part of their normal configuration deployment strategy.

view instance is a set of configurations that describes how data in Drupal will be collected and presented to the site’s visitor. A single view can have multiple displays. Possible view displays include a page available under certain URL path, a block to be placed in a theme region, or a feed to be exported in RSS or OPML formats. Each type of display will allow you to specify a presentation format. Possible values vary per display type. In the case of a page display, valid alternatives include unformatted liststablesHTML lists, and grids. Display and output formats are provided by modules. As you enable more core modules or install new contributed modules, you might get more options. Visit this page for a list of modules that extends Views functionality.

Tip: The Views UI contains some inconsistencies that might confuse you if you are not familiar with it. One is that it uses the word “Content” to refer to nodes, like in the first page of the views creation wizard. Another is that, contrary to the “URL alias” setting in the node edit page, the path setting inside a view does not produce a validation error if it does not start with a / (slash) sign. These and other subtle differences exist, but they are negligible compared to all the benefits we get from using the system.

Technical note: It is possible to see the SQL query that Drupal executes to fetch the list of results. Go to the “Views settings” page under /admin/structure/views/settings and check the “Show the SQL query” option of the “Live preview settings.” Then you can go to any view and upon clicking the “Update preview” button you will see the SQL query issued by Drupal. As an example have a look at the view that shows the frontpage configured under /admin/structure/views/view/frontpage Note that table names are enclosed by curly brackets ({}). This is because Drupal allows you to define table prefixes to share the database with other applications. Although they is rarely useful, it is possible to configure them. To accommodate for this, the Views API uses curly brackets to indicate that table names need to processed to prepend table prefixes when they are set.

How do Drupal views work?

This section assumes the Views UI module is enabled. In order to create a view you visit the “Add view” page under /admin/structure/views/add. For “View settings > Show” you need to specify which type of listing you want to create: content (nodes), users, comments, files, etc. You can also indicate how you want to present the results: a page with an optional RSS feed or a block. After this initial form you are taken to the complete setup interface where the configuration options are virtually endless. The initial selection for what to show (content, users, etc.) cannot be changed once set because it serves as the base table to collect data from. Except for that and the machine name of the view, every setting can be changed at any point using this interface. Instead of creating a view from scratch, let’s review some examples that come with the standard installation profile in Drupal. This will allow us to better understand the Views UI interface.

The frontpage view is configured under /admin/structure/views/view/frontpage. It comes with two displaysPage and Feed. The Page will appear under the /node path with a format of an unformatted list showing Content (nodes) using the Teaser view mode. Because we are showing a view node, there are no individual fields to present. Using view modes is recommended over rendering fields. One reason is that it benefits from caching at the entity level. The filter criteria section specifies the conditions that must be met by a node to appear in the final list of results. In this case, the node needs to be published and promoted to the frontpage. Note that there is no filter criteria for content type. Yet, in a default Drupal installation all articles appear in the frontpage and no basic pages appear there. The reason is because, by default, articles are set to be promoted to the frontpage while basic pages are not. This setting can be changed on a node basis and defaults can be set on a content type basis.

Back the the Views UI for the frontpage view, in the sort criteria section we see two values. The first will put any node marked as sticky at the top of the list. The second will order the nodes based on their creation date. When there is more than one sort criteria, the order in which they are defined is important. Any criteria that appears first in the list will take precedence over subsequent ones. This view display is used by Drupal’s default frontpage. Note that its path /node is set as the frontpage under /admin/config/system/site-information in a standard installation. The second display of the view is a Feed whose configuration is mostly the same as the Page display. The relevant differences are the path, format, and view mode setting: /rss.xml, RSS Feed format, and RSS view mode, respectively.

Sometimes, we want to create a view to present a list of elements, but we want the end user to further filter down that list or change the way it is sorted. It is possible to do this using exposed filters and exports sorts. A good example is the administration interface for all the nodes in Drupal that lives under /admin/content. The configuration for this view is available at /admin/structure/views/view/content. This view presents seven fields in table format: node operations bulk form, title, content type, author, publication status, updated timestamp, and operations. In the filter criteria section, four elements have been exposed allowing the content editor to filter the list based on node title, content type, publication status, and language. This view does not offer any exposed sort criteria, but its functionality and presentation is similar to that of exposed filters. However, because it uses a table format, some of the headers were made clickable allowing changing the order ascending or descending for that particular field. This is yet another way of allowing the end user override how the results are presented by default.

It is important to note four things in the previous example. First, a view field is not always a field attached to a content type, like the one providing the “operations” column in the table. The reuse of the word “field” in this context is a bit unfortunate. Second, the list of fields in the fields section and the filter criteria section does not have to be the same. Third, the widget (text input, drop down, etc.) that will allow the user to filter down the list depends on the type of field that is being processed. Fourth, when the user filters down the list, the original presentation format is kept, a table with seven columns in this case.

Tip: Drupal core comes with at least 14 default views. Studying them is a good way to learn more about how the Views system works. For the curious reader, have a look at the “Who’s new” and the “Who’s online block” views for examples of block displays. Both are available at /admin/structure/views. If you want to play with them without having to setup a local development environment, I recommend using https://simplytest.me/ In that website you can test Drupal core and contributed modulesthemes, and distributions within minutes.

Technical note: Being a SQL query builder, some elements of the Views UI can be mapped to SQL concepts. The fields section maps to table columns to include in the SELECT statement. Relationships add JOIN clauses to the query. The filter criteria and contextual filters sections map to the WHERE clause. The sort criteria section maps to ORDER BY clause. The pager adds LIMIT and OFFSET clauses. Using aggregation adds a GROUP BY clause to the query. And the “Distinct” query setting adds a DISTINCT clause. Be aware that interface elements do not map one to one to SQL query elements. The Views UI strives to hide the complexity of the underlying data structure from site builders. Although not required, understanding this mapping is useful, especially when the view configuration does not yield the expected result.

Dynamic results

Views is one of the many systems that allow you to create dynamic sites with Drupal. These sites that, once configured, update their content automatically as time passes. For example, if you have a website that contains information about events, you might want to have a page that lists only future events. To accomplish this you can create an “Event” content type that has a “date” field. Then you create a view with a filter criteria that uses this field so that only events whose date is “today” or greater appear on the final list. Note that it is possible to use date offsets as filter values. Once all the configuration is in place, content editors only need to add nodes and set a value for the “date” field. When Drupal shows the page for this view, it will respect the original configuration and only show results that match the condition from today onwards. This illustrates the need to store node data in separate fields. This way you can use them as fields (to show), filter criteria, sort criteria, and more. If you had this information inside the “body” field, it would be practically impossible to use it for these purposes.

Views with only one result

We said that views are used to create a listing of elements. When talking about lists, it is common to think of results with more than one element, usually many. But there are some cases where creating views of one element make sense: when you want to show “the most of”, “the best of”, or other superlatives. For example, the most visited article in the last month, the most attended event last year, the most recent product added to the store, etc. Another use case for a view of one element is when you want to show something random. To accomplish this, you add a single sort criteria aptly named “Random.” In all of these cases, the pager would be configured to show only one element.

Other use cases

The use cases for Views are endless. Some will require the use of contributed modules, but it is possible to build many things with core Views functionality. Here is a very short list of things that you can built with Views:

  • An interactive map like the one at Drupical.com.
  • A JSON or CSV representation of some content that you want to migrate from Drupal 7 to Drupal 8 using the Migrate API.
  • A search page with exposed filters and facets using the Search API.
  • An audio or video player with a playlist feature.
  • An (image) carousel, although that is very likely a terrible idea.

The power is yours

Views is an extremely powerful system and a key differentiator of Drupal compared to other content management systems (CMSs) and frameworks. We have only scratched the surface of what is possible in this blog post. Core Views has many other concepts like contextual filters and relationships that were not explained. Using contributed modules or custom code you can flex Views to match specific needs. For example, you can extend Views using plugins to create your own fields, filter criteria, sort criteria, etc. You can also use hooks to alter the SQL query itself. Additionally, you can rewrite results and theme the output. With so many moving parts, it might be daunting to learn Views. My recommendation is to learn one concept at a time and tinker with existing views, like the ones that come with Drupal core, to learn how they work.

About 8 years ago, Johan Falk created one of the best resources to learn Views I have seen so far. Similarly to the Drupal concepts we have been learning so far, Views concepts have not changed significantly since the release of that video series. Kudos to Johan for creating many valuable Drupal tutorials back in the day. Maybe some time in the future I will be able to produce a similar/updated Views tutorial here at UnderstandDrupal.com Drop me a line if you would be interested in sponsoring such endeavor.

How familiar were you with Drupal Views? Did you know how different elements of the Views UI map to SQL query clauses? What are some concepts that you find hard to understand? What contributed modules do you know that extend Views functionality?