mcpField
D
drupal-paragraphs

drupal-paragraphs

github.com/edutrulDevelopment7350 installsUpdated 21w ago
Repository

About drupal-paragraphs

A Drupal development skill for working with Paragraphs entities and fields. It covers programmatic creation, form alteration, rendering, and Twig access.

Key features

  1. 01Read referenced paragraphs
  2. 02Create Paragraphs programmatically
  3. 03Alter paragraph forms
  4. 04Render paragraphs and access them in Twig

Use cases

  1. 01Read paragraph field values from a node
  2. 02Build paragraph entities in code
  3. 03Change paragraph form elements by bundle
  4. 04Render paragraph content in Drupal or Twig

Install

Copy the command and run it in a terminal.

$npx skills add https://github.com/edutrul/drupal-ai --skill drupal-paragraphs

After installing, type/drupal-paragraphsin Claude Code to confirm it loaded.

Bundled filesREADME.md

Details

From the project README

Drupal Paragraphs

Accessing Paragraphs from a Node

use Drupal\paragraphs\Entity\Paragraph;

// Get all paragraphs from a field
$items = $node->get('field_content')->referencedEntities();
foreach ($items as $paragraph) {
  /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
  $bundle = $paragraph->bundle();
  $value = $paragraph->get('field_text')->value;
}

// Get first paragraph
$paragraph = $node->get('field_content')->first()?->entity;

Creating Paragraphs Programmatically

$paragraph = Paragraph::create([
  'type' => 'text_block',
  'field_title' => 'My Title',
  'field_body' => [
    'value' => 'Body content',
    'format' => 'basic_html',
  ],
]);
$paragraph->save();

$node->get('field_content')->appendItem([
  'target_id' => $paragraph->id(),
  'target_revision_id' => $paragraph->getRevisionId(),
]);
$node->save();

Altering Paragraph Forms

#[Hook('field_widget_single_element_paragraphs_form_alter')]
public function fieldWidgetParagraphsFormAlter(array &$element, FormStateInterface $form_state, array $context): void {
  $paragraph = $element['#paragraph'];
  if ($paragraph->bundle() === 'text_block') {
    // Alter the text_block paragraph form element.
    $element['subform']['field_title']['#access'] = FALSE;
  }
}

Rendering Paragraphs

// Build render array for a paragraph
$view_builder = $this->entityTypeManager->getViewBuilder('paragraph');
$build = $view_builder->view($paragraph, 'default');

Paragraph in Twig

{# Render paragraph field #}
{{ content.field_content }}

{# Iterate paragraphs #}
{% for item in content.field_content['#items'] %}
  {{ item.entity.field_text.value }}
{% endfor %}

Common Bundle Check Pattern

foreach ($node->get('field_content')->referencedEntities() as $paragraph) {
  /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
  switch ($paragraph->bundle()) {
    case 'text_block':
      // Handle text block.
      break;
    case 'image_block':
      // Handle image block.
      break;
  }
}

Comments

Markdown supported