Add references to previous and next siblings of the current node

Created on 24 April 2024, 8 months ago

Problem/Motivation

The JSON:API Book module adds useful elements under the drupal_internal__book key of the JSON response. However, one sometimes need to access the previous and next pages of the current book page.

Proposed resolution

Add two new elements nid_prev and nid_next containing the nids of the previous and next nodes if they exist. The code below shows a minimalist working modification of the file ResponseSubscriber.php :

...
  private function findBookDefinition(array &$record): void {
    ...
    if (!isset($this->loadedBookDefinitions[$nid])) {
      ...
      if (!empty($this->loadedBookDefinitions[$nid])) {
        ...
        foreach ($references as $reference) {
          ...
        }
        // Add references to previous and next siblings of the current node
        /** @var \Drupal\book\BookOutline $book_outline */
        $book_outline = \Drupal::service('book.outline');
        $book_link = $this->bookManager->loadBookLink($nid, FALSE);
        $prev = $book_outline->prevLink($book_link);
        $next = $book_outline->nextLink($book_link);
        $this->loadedBookDefinitions[$nid]['nid_prev'] = $prev['nid'];
        $this->loadedBookDefinitions[$nid]['nid_next'] = $next['nid'];
      }
    }
  }
...

Remaining tasks

Test and improve this code.

✨ Feature request
Status

Active

Version

1.1

Component

Code

Created by

πŸ‡¨πŸ‡­Switzerland boregar

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024