Add references to current node (e.g. previous/next/first/last/count)

Created on 24 April 2024, 2 months ago
Updated 23 May 2024, about 1 month 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, the first and last pages of the book or simply get the number of pages.

Proposed resolution

Add new elements nid_prev, nid_next, nid_first, nid_last, nid_count. 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'];
        // only add first/last/count informations if we are at the top of the book hierarchy
        if ($this->loadedBookDefinitions[$nid]['nid'] === $this->loadedBookDefinitions[$nid]['bid']) {
          $toc = $book_outline->childrenLinks($book_link);
          if (is_array($toc) && array_key_exists('#items', $toc)) {
            $this->loadedBookDefinitions[$nid]['nid_first'] = array_key_first($toc['#items']);
            $this->loadedBookDefinitions[$nid]['nid_last'] = array_key_last($toc['#items']);
            $this->loadedBookDefinitions[$nid]['nid_count'] = count($toc['#items']);
          }
        }
      }
    }
  }
...

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.69.0 2024