- Issue created by @boregar
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.
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']);
}
}
}
}
}
...
Test and improve this code.
Active
1.1
Code