← Back to postsWrapping Your Head Around Entity-Reference Views

Wrapping Your Head Around Entity-Reference Views

Published: 7/12/2017

While cross-training a colleague on Drupal Views, I had to reacquaint myself with the usage of Entity References and Relationships. It's not uncommon for me to build Views that use those features, but once they're built, they just work, and I rarely have to touch them again. Since I initially found myself stumbling over these steps, I though it might be good to document our example.

Here was our situation...

We created two sample content types in a test site: Artist and Album.

The Artist content type was as basic as possible, just Title, Body, and Photo fields.

The Album content type had a few more fields, including an Entity Reference to the appropriate Artist node.

After populating our test site with some sample content, we wanted to display a list of Albums on the Artists' pages. For example, the page for Red Hot Chili Peppers should display a list of Albums like Stadium Arcadium, and Blood Sugar Sex Magik.

But the Artist content had no references to Albums. Instead, the opposite was true: the Album content contained the entity reference back to Artist.

We knew we wanted the fields Title and Album Cover from published content of type Album. We also knew we would need to add a relationship to field_artist. And this is where it's easy to get things backwards, especially when you're trying to explain Views and Entity References to someone who isn't familiar with them. When adding the Relationship, the default language for the identifier was "Content entity referenced from field_artist." Obviously, we could have changed this to any value, but I found it helpful to talk this through with my trainee: the field_artist is in the Album content type, and we're displaying fields from the Album content type, knowing that field_artist is what ties the two content types together...so what we're doing is correct.

But for this view, the key to displaying the correct results was in setting a Contextual Filter on Node ID (Nid). Without the Contextual filter, we'd get a list of every album, not just the ones belonging to the Artist. The Contextual Filter needed the Relationship that we just established, and we needed to provide a default value of "Content ID from URL."

Our view was created in a Block, so after saving our view, we had to tell the Block to display on every page. The Contextual Filter and Relationship assured that it only displayed where we wanted it.

Below are screenshots of our final View configuration and our block.