How to filter a view by content that references the current node in modern Drupal
References and contextual filters
It is often enough throughout the journey of building websites that you will desire to create very specific lists of content. In my current endeavor, I am working in Drupal 9 with 2 content types: Office location and Event . Each Event occurs at an Office location, which is indicated by an Office location entity reference field on the Event. Note that any info in this blog will also be relevant to Drupal 8, Drupal 10, and beyond.
Here is the user story that we will be working through:
As a site visitor, when I view an Office location node, I should see a list of Events that are occurring at the location represented by the current node, so that I have an easy way to learn about events at locations relevant to me.
To keep this short and sweet, I am going to assume that you have already created a view. However, all views are not created equal, so if you are not seeing the options that you are looking for while editing your view, maybe try creating a new one. We will be working with a
block display—other options are possible, but this is the standard "Drupal approach".
Once you are editing a block display for your view, open the
Advanced dropdown on the right side. Here is what you will see:
1, Add a relationship to content referenced by your entity reference field
Go ahead and click the
Add button next to
In my case I am looking for
Content referenced from field_office_location. This is the entity reference field on my
Event content type, and is the field that my view will use for comparison while querying data.
Click add and configure relationships and then
Apply on the next screen.
2. Filter your view results by content that references the current node id
Add button next to
ID and click
Add and configure contextual filters.
The red boxes above indicate what needs to be done. Be sure to select the relationship you added to the
Relationship field. This will allow the contextual filter to use the value of the Event's entity reference field for comparison.
Provide default value and select
Content ID from URL in the dropdown that appears. Note that if your nodes have URL aliases that do not include the content ID, Drupal will still provide the content ID to your contextual filter. Now your view will know which content to display by comparing the current node ID with the the values in the entity reference field of each listing.
Apply and do not forget to save your view.
Congratulations! Now we know how to filter our view by content that references the current node. You probably still need to place your block and configure which nodes it should or should not display on, but I think that is a "How to" for another day. Have fun Drupaling!