0

For a given content type, if a new node is created and no book is assigned, I'd like to create a new book and assign the new node to that book.

(some background - that content type is the book cover, and for editors to create a new book I ask them to create a cover first. this makes more sense for them. The 'add child page' links will then appear automatically. I know they can select 'new book' on the create page, but that makes no sense in that context - alternatively, if I could have that selected by default, that would work )

1
  • note to self: create a new book is misleading here, because a book is not an entity.
    – commonpike
    May 4 at 6:47

2 Answers 2

1

you can use a hook implementation in a custom module

    /**
 * Implements hook_node_insert().
 */
function mymodule_node_insert($node) {
  // Check if the node is of the desired content type and no book is assigned.
  if ($node->getType() == 'my_content_type' && empty($node->book['bid'])) {
  // Get the book storage handler.
  $bookStorage = \Drupal::entityTypeManager()->getStorage('book');

  // Create a new book entity.
  $book = $bookStorage->create(array(
    'type' => 'book',
    'title' => $node->getTitle(),
    'uid' => $node->getOwnerId(),
  ));
    $book->save();

    // Assign the node to the new book.
    $node->book['bid'] = $book->id();
    $node->book['plid'] = 0;
    $node->save();
  }
}
2
  • Thanks! Allthough - apparently, I do not want to 'create new book' because book is not an entity. I just want to 'assign a new book'. I got a working version from your code, but adding it as a separate answer.
    – commonpike
    May 4 at 6:43
  • Yes, a book is not a content entity, which means there is not any storage handler for books and \Drupal::entityTypeManager()->getStorage('book') will not return any class instance.
    – apaderno
    May 5 at 20:21
0

Using @rafael 's answer:

/**
 * Implements hook_node_insert().
 *
 * - assigns a new book for a new MYCONTENTTYPE if none was selected
 */

function MYMODULE_node_insert($node) {
  if ($node->getType() == 'MYCONTENTTYPE' 
    && property_exists($node,'book') 
    && empty($node->book['bid'])) {
      $node->book['bid'] = 'new';
      $node->book['plid'] = 0;
      $node->save();
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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