Drupal 9 —Pre-polulating paragraphs blocks

Deeps
2 min readJul 28, 2022

We have a content type where there are few nested paragraphs which is fairly easy to add. However some one those nested paragraphs are almost added to all content which mean editors need to Add first level paragraphs, add some content, second level paragraph, add more content, add third level paragrahs and more content.

So what I tried to do is to create those nested paragraphs when new content is created so that content edit can quickly add content. Here is how paragraphs structure looks like.

Node
— Paragarphs field (section)
— — Paragraphs field (sub_section)
— — — Paragraphs field (sub_sub_section)

Here is what I did in order achieve this.

/**
* Implements hook_entity_create().
*/
function my_module_entity_create(EntityInterface $entity) {
/** @var \Drupal\node\NodeInterface $entity */
// On new article pages.
if ($entity->bundle() == 'article' && $entity->isNew() && $entity->hasField('node_field_name')) {
// Create a last child.
$sub_sub_section = Paragraph::create([
'type' => 'sub_sub_section'
]);
$sub_sub_section->isNew();
// Create a parent of last child.
$sub_section = Paragraph::create([
'type' => 'sub_section',
]);
$sub_section->isNew();
// Create a grand parent of last child.
$section = Paragraph::create([
'type' => 'section',
]);
// Add the nested sub_sub_section to the paragraphs.
$sub_sub_section_blocks = $sub_sub_section->get('sub_section_field_name');
$sub_sub_section_blocks->appendItem($sub_sub_section);
$sub_sub_section_blocks->isNew();
// Add the nested sub_section/sub_sub_section to the paragraphs.
$section_blocks = $section->get('section_field_name');
$section_blocks->appendItem($sub_section);
$section_blocks->isNew();

// Add the nested section/sub_section/sub_sub_section to the node's field.
$field = $entity->get('node_field_name');
$field->appendItem($section);
}
}

So basically, you create a lowest level child field and append it to parent paragraphs and append parent paragraphs to grand parent paragraphs and finally grand parents paragraphs to node field.

With this method you can add as many nested item as your paragraphs field allows.

--

--