I have studied create nodes programmatically and create a book page but still i did not find how to create and add a page to the existing book. How to set parent child relationship if applicable. I am using Drupal 8. Can anybody help please?


You can use the saveBookLink(array $link, $new) method of the BookManager service (book.manager). See Drupal\book\BookManagerInterface.php

After you create the node programmatically, create a new array $link with the following key/value components:

Each book entry consists of the following keys:
 - bid: The node ID of the main book.
 - nid: The node ID of the book entry itself.
 - pid: The parent node ID of the book.
 - has_children: A boolean to indicate whether the book has children.
 - weight: The weight of the book entry to order siblings.
 - depth: The depth in the menu hierarchy the entry is placed into.

(See Drupal/book/BookOutlineStorageInterface::loadMultiple()).

So, your code will look something like this:

protected $bookManager;

public function __construct(BookManager $bookManager) {
  $this->bookManager = $bookManager;

public static function create(ContainerInterface $container) {
  return new static(

/** Method that creates your node here... **/
  $link = [
    'nid' => $nid,
    'bid' => $bid,
    'pid' => $pid,
    'weight' => $weight,

  $this->bookManager->saveBookLink($link, TRUE);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.