Skip to content

Instantly share code, notes, and snippets.

@AronNovak
Last active December 12, 2022 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AronNovak/96bcfa90baaa75072eec163eba0deca6 to your computer and use it in GitHub Desktop.
Save AronNovak/96bcfa90baaa75072eec163eba0deca6 to your computer and use it in GitHub Desktop.
Programmatic hierarchical book structure
<?php
// Create seven nodes, put them in a book tree structure.
// A
// |- B
// | |- C
// | |- D
// |- E
// |- F
// |- G
use Drupal\node\Entity\Node;
$node_a = Node::create([
'type' => 'page',
'title' => 'A',
'book' => [
'bid' => 'new',
'pid' => 0,
'weight' => 0,
],
]);
$node_a->save();
$node_b = Node::create([
'type' => 'page',
'title' => 'B',
'book' => [
'bid' => $node_a->id(),
'pid' => $node_a->id(),
'weight' => 0,
],
]);
$node_b->save();
$node_c = Node::create([
'type' => 'page',
'title' => 'C',
'book' => [
'bid' => $node_a->id(),
'pid' => $node_b->id(),
'weight' => 0,
],
]);
$node_c->save();
$node_d = Node::create([
'type' => 'page',
'title' => 'D',
'book' => [
'bid' => $node_a->id(),
'pid' => $node_b->id(),
'weight' => 1,
],
]);
$node_d->save();
$node_e = Node::create([
'type' => 'page',
'title' => 'E',
'book' => [
'bid' => $node_a->id(),
'pid' => $node_a->id(),
'weight' => 1,
],
]);
$node_e->save();
$node_f = Node::create([
'type' => 'page',
'title' => 'F',
'book' => [
'bid' => $node_a->id(),
'pid' => $node_e->id(),
'weight' => 0,
],
]);
$node_f->save();
$node_g = Node::create([
'type' => 'page',
'title' => 'G',
'book' => [
'bid' => $node_a->id(),
'pid' => $node_e->id(),
'weight' => 1,
],
]);
$node_g->save();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment