How to use Contextual Filter in Drupal 8
Contextual filters in Views are powerful, but getting them to work perfectly can be a tricky sometimes. This will hopefully save some people from the headache I had gone thru’. Contextual Filters in Drupal 8 are similar to the Drupal 7 with advance feature and more dynamic compared to normal filter. A Contextual Filter provides more convenient way to fetch the data either from variables sent programmatically or URL.
A contextual filter for a node author would be able to display all nodes written by the currently logged in user.
My goal was to have a page of Articles that could be filtered based on logged in user. In this tutorial we will use author relationship to get the name of the author and use it in a Display summary to list all the users with some additional information.
Step 1: We have to go through basic View Page creation by visiting /admin/structure/views/add
Fill up View Basic information, Page settings detail and click on Save and edit.
I have created a view with below input.
View Basic Information
View name: Article_by_You
Description: listing article created by logged in User
of Type: Article
Page Title: Article_By_You
Page Display Settings
Display format: Table
Step 2: Once we have done with Step1, next we would be redirected to View Settings Page. Here I have added Body, Authored by & Authored on under Fields Section. Now click the Advanced Section on extreme right and click on CONTEXTUAL FILTERS “Add” button.
Content: Authored by (Authored by)
Content: Authored on (Authored on)
Step 3: Search For “Authored by” and click on Apply (all displays).
Step 4: Select “Provide default value” under WHEN THE FILTER VALUE IS NOT IN THE URL & Select Type as “User ID from logged in user” and click on Apply (all displays).
Step 5: So, we are done with view creation. It’s time to review by visiting
the URL: example.com/d8/article-by-you
This page is showing articles created by logged in users and we don’t have to pass any additional argument. Try logging with some other user credentials and visit article-by-you page to test the view we have created just now.