Score:0

How do I programmatically assign a new book when a new node is created?

in flag

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 )

commonpike avatar
in flag
note to self: `create a new book` is misleading here, because a book is not an entity.
Score:1
uz flag

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();
  }
}
commonpike avatar
in flag
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.
apaderno avatar
us flag
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.
Score:0
in flag

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();
  }
}
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.