I have 2 content types: Books and Chapters.
Books have an entity reference field that can accept unlimited values. Chapters have an entity reference field (single value) that corresponds to a book.
These entity reference fields are "linked" with the Corresponding Entity References module.
My goal is to create a block that will be displayed at the top of the Chapter nodes that will act like a pager of some sort and will display the previous and next chapters from the one that is being viewed.
For example, when someone views Chapter 1 of a book, the block will show:
- Chapter 1 (no link)
- Chapter 2 (link to Chapter 2)
- Chapter 3 (link to Chapter 3)
- Chapter 4 (link to Chapter 4)
- Chapter 5 (link to Chapter 5)
When someone is viewing Chapter 10, the block will show:
- Chapter 8 (link to Chapter 8)
- Chapter 9 (link to Chapter 9)
- Chapter 10 (no link)
- Chapter 11 (link to Chapter 11)
- Chapter 12 (link to Chapter 12)
and when someone is viewing the last chapter (say chapter 25):
- Chapter 21 (link to Chapter 21)
- Chapter 22 (link to Chapter 22)
- Chapter 23 (link to Chapter 23)
- Chapter 24 (link to Chapter 24)
- Chapter 25 (no link)
My immediate thought was to create a view, but after I have created the view with the proper contextual filter and relationship, there was no option to sort the results based on the weight of the Chapter in the Book's entity reference listing.
I then tried to use Views PHP and sort the results via PHP with code like that:
$node = node_load($row1->nid);
$weights = $node->field_book_contained_chapter['und'];
array_walk($weights, function (&$v, $k) { $v = array_shift($v); });
return array_search($row1->nid_1, $weights) - array_search($row2->nid_1, $weights);
which works fine only if you select to display all items (doesn't work with pagers) but is also very inefficient: it runs through the whole array of referenced entities for every comparison between two rows (and some of my books have more than 1300 chapters). I haven't tested how it performs but my gut tells me that it's not a very elegant solution (I will also have to do additional filtering after I sort them).
Now I'm thinking about creating a custom block with php code that will traverse the $node->filed_book_contained_chapter['und'] array and find the neighboring articles of the current article. This seems like a more efficient solution than the views' one, but still feels kind of an awkward approach.
Is there an obvious way that I'm missing to achieve the functionality that I'm after?