Category: Development

Entity reference filter with Drupal 8

Author(s)

Luc
Luc
We enjoy new challenges and recently decided to build a new project on Drupal 8. We already love it and look forward to seeing it grow! Of course, we're running into some small issues here and there and as resources are still scarce, we wanted to share our small experience with you.
We're dealing with articles linked to events by entity reference and we need to be able to filter the articles view by related Event.
Content type - Article
| Field         | type                                   |
|---------------|----------------------------------------|
| title         | text                                   |
| …             | …                                      |
| related_event | entity reference : type event or story |
Content type - Event
| Field | type |
|-------|------|
| title | text |
| …     | …    |
The module Better Exposed Filter used to do the trick with Drupal 7 but is not ported to Drupal 8 yet.
As D8 is now in an almost stable state, we decided to investigate in order to fulfill this need.

Solution

Danny Sipos is explaining how to create a custom filter for views in D8 on his Web Omelette tutorials blog.
That's already a good base for what we need but filter options are hard coded in this example.
In our case, we have to consider the relation between an article and his related event/story. So we need to target the node id instead of title and consider the relation between these two entities.modules/custom/mymodule/mymodule.views.inc
<script src="https://gist.github.com/dmrrlc/513cc522bbb0eaaad25b.js"></script>
modules/custom/mymodule/src/Plugin/views/filter/RelatedContentTitles.php
<script src="https://gist.github.com/dmrrlc/7418fd68f9f2f483a8e6.js"></script>
There are 2 important points in this file :
  • The @ViewsFilter("mymodule_related_content_titles") annotations tells Drupal that this ViewFilter is linked the the previous declaration in mymodule.views.inc
  • The inOperator extension from the Web Omelette totorial is replaced by ManyToOne because we are using a relation field

The logic part is now done

We still need to configure the Drupal 8 view
1. Create a new view listing Articles elements
2. Add the relationship
Under advanced view settings, add a new relationship on field of type : Content: Content referenced from field_related_event
3. Add the filter
Add a new contextual filter of our custom type : Content: Related content titles
check the box Expose this filter to visitors and select the previously created relationship
custom filter
And there you go!