Entity reference filter with Drupal 8
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
|related_event||entity reference : type event or story|
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.
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.
There are 2 important points in this file :
@ViewsFilter("mymodule_related_content_titles")annotations tells Drupal that this ViewFilter is linked the the previous declaration in
inOperatorextension from the Web Omelette totorial is replaced by
ManyToOnebecause 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
And there you go!