Combine photos from parent node and referenced nodes into a single list (for slideshow)

drupal.stackexchange https://drupal.stackexchange.com/questions/300279

  •  02-03-2021
  •  | 
  •  

Question

Drupal 8

I have two content types. Department and Employee.

Department has an entity reference field that references Employee(s).

Department and Employee both have a field called “field_photos”. (Same field name in both).

In views (or via Twig in a node template), I’d like to display all “field photos” from both the Department Node AND Employee(s) nodes referenced by that Department… into a single list output.

So the end output will be a slideshow for each department showing all “field_photos” from that Department and referenced Employees.

Was it helpful?

Solution

As always there is more than one way of solving problems in Drupal. There is a way you could build a DB query with only Views that would combine the ER reference through Relationships.

But there is a way to solve this that is (arguably) "more Drupal", and that with the help of Content View Modes. They are not to be confused with Views module, we will actually combine the two separate features, View modes and Views (module), to build your solution.

Use View Modes on ER Fields in Views

View modes are different combinations of entity fields visibility and output settings. With View modes you can create many different "views" of the same content. For example, "Full" and "Teaser" are ubiquitous View Modes.

In your case you want a special View Mode of the Employee CT that shows their photos. Create a new View mode on the Structure > Display modes > View modes (you can also get to this page through each CT "Manage display" page).

Enable that mode, visit it (it becomes a sub-tab) and disable all Fields you don't need, configure the photos field to your liking.

In Views create a list of all Departments, add the Photos and Employees ER Fields.

When configuring the Employees field set the Formatter to the View mode you had created especially for this. ER fields usually only show ID of the referenced entities, exceptionally their titles, but with View modes you can pull any info from the referenced item.

This is how you get a list of all Departments with all the Department and referenced Employees photos listed.

Slideshow

The slideshow part of the Q depends on how you plan to build that in. You'll probably use some external library with a module that implements it into Views.

Depending on how a particular library and module work you will be able to apply it to each Views row, or to each Field.

To combine photos from both fields use the Exclude from display on the top field and Rewrite results on the bottom field. Use Replacement patterns to construct the HTML output that your slideshow library can use. In some cases you'll need to override with twig templates.

Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top