Views - Basics in Drupal 8/9

Views - Basics in Drupal 8/9

How to use views to build pages and blocks

In early days, people were doubtful about using views and thought of views for only basic stuff. Back then, views was a contributed module. As drupal 8 was announced the views module was integrated into the drupal core and it's full potential was unlocked.

Views are like custom queries that we can create using drag and drop. By query, we mean we can choose what type of content we want to show, it's fields, sorting orders and pagination. We can even join multiple tables using views.

First of all, let's decide what we want and how we will do it. Our requirement is we need a page that shows list of news (content type: News) by order of date it was updated. We also need a search input text so that user can search for a news. This page should support pagination as well.

blog5-1.png

Let's get started.

First we go to the views admin page in "admin/structure/views" and then click on the "Add view" button. When creating view, we can have two options, either we create a page or a block or both. We can choose what type of content type list we want to make, for this example, we are choosing "News" and select "Create a page".

blog5-2.png

Now let's have a look at the views configuration form. There are three parts on this page. First Column contains the SELECT, WHERE and SORT BY part of the query. We can choose what fields we want to display on the list, put condition like content is published and sort by specific field value.

blog5-3.png

Now, if we go to the path "/news-list" we will see our newly created page with list of News.

Let's quickly talk about how can we theme this page. We are currently using "Unformatted list" as our views format. So, we can go to "/core/modules/views/templates" and open the "views-view-unformatted.html.twig" file. We can see that the list is coming in "rows" variable and a loop has been used to render the news. Do not edit this file, instead copy this file and bring it to the custom theme folder and edit there. You need to clear the cache in order for Drupal to scan this new template file.

image.png

You can remove caching during development and then inspect the page, this will show how you can theme specific part of the page.

[ drupal.org/node/2598914 ]

That's all for views basic in Drupal 9. In next blog post, I will explain how to theme the views in detail. Thank you for reading such long post.