CMS Drupal Mastering Development

Navigate to next page / previous page based on entity reference field instead of Book module

I am trying to create next/previous page links like the Book module.

I have two content types, Chapter and Page.

The Chapter content type contains an entity reference field (unlimited) for pages.

So, each chapter contains an arbitrary number of pages in the entity reference field Pages in Chapter, and these are re-ordered to determine the order of the pages.

Now, on each Page, I want to make links to the previous and next pages based on the values of the parent Chapter‘s entity reference field Pages in Chapter.

Specifically, using a view or block or similar on the Page, I need to get the Chapter that references the current Page, iterate through the values of the entity reference field Pages in Chapter, find the Page that is immediately before and the Page that is immediately after the current Page, and then output this as a simple unordered list.

I can code a little but I’m not very good so I’m having trouble finding an approach to implement this.

What I tried

I tried to build this in Views. The problem I encountered was that it is very difficult to iterate through the subdivision entity reference field and filter out the previous and next links.

This is a similar question for Drupal 7 but since Drupal 8 includes so much more in core (Views and Entity References, for example), I think it’s fair to ask the question again.

Why not just use the Book module?

I only need the next/previous page functionality, and ideally it would be based on my entity reference field Pages in Chapter. The book module navigation in Drupal 8 doesn’t follow the same patterns as the rest of core (it’s not a block, and it’s not a menu). I spent a couple hours this afternoon going through the Book issue queue and cleaning up old issues, and it seemed there is very little effort to “modernize” the module, so I thought it would be better to try to implement this feature on my own.

Leave a Reply

Your email address will not be published. Required fields are marked *