$npx -y skills add edutrul/drupal-ai --skill drupal-paragraphsDrupal Paragraphs module — accessing paragraph entities, rendering, altering paragraph forms, and patterns for custom paragraph behavior.
| 1 | # Drupal Paragraphs |
| 2 | |
| 3 | ## Accessing Paragraphs from a Node |
| 4 | |
| 5 | ```php |
| 6 | use Drupal\paragraphs\Entity\Paragraph; |
| 7 | |
| 8 | // Get all paragraphs from a field |
| 9 | $items = $node->get('field_content')->referencedEntities(); |
| 10 | foreach ($items as $paragraph) { |
| 11 | /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */ |
| 12 | $bundle = $paragraph->bundle(); |
| 13 | $value = $paragraph->get('field_text')->value; |
| 14 | } |
| 15 | |
| 16 | // Get first paragraph |
| 17 | $paragraph = $node->get('field_content')->first()?->entity; |
| 18 | ``` |
| 19 | |
| 20 | ## Creating Paragraphs Programmatically |
| 21 | |
| 22 | ```php |
| 23 | $paragraph = Paragraph::create([ |
| 24 | 'type' => 'text_block', |
| 25 | 'field_title' => 'My Title', |
| 26 | 'field_body' => [ |
| 27 | 'value' => 'Body content', |
| 28 | 'format' => 'basic_html', |
| 29 | ], |
| 30 | ]); |
| 31 | $paragraph->save(); |
| 32 | |
| 33 | $node->get('field_content')->appendItem([ |
| 34 | 'target_id' => $paragraph->id(), |
| 35 | 'target_revision_id' => $paragraph->getRevisionId(), |
| 36 | ]); |
| 37 | $node->save(); |
| 38 | ``` |
| 39 | |
| 40 | ## Altering Paragraph Forms |
| 41 | |
| 42 | ```php |
| 43 | #[Hook('field_widget_single_element_paragraphs_form_alter')] |
| 44 | public function fieldWidgetParagraphsFormAlter(array &$element, FormStateInterface $form_state, array $context): void { |
| 45 | $paragraph = $element['#paragraph']; |
| 46 | if ($paragraph->bundle() === 'text_block') { |
| 47 | // Alter the text_block paragraph form element. |
| 48 | $element['subform']['field_title']['#access'] = FALSE; |
| 49 | } |
| 50 | } |
| 51 | ``` |
| 52 | |
| 53 | ## Rendering Paragraphs |
| 54 | |
| 55 | ```php |
| 56 | // Build render array for a paragraph |
| 57 | $view_builder = $this->entityTypeManager->getViewBuilder('paragraph'); |
| 58 | $build = $view_builder->view($paragraph, 'default'); |
| 59 | ``` |
| 60 | |
| 61 | ## Paragraph in Twig |
| 62 | |
| 63 | ```twig |
| 64 | {# Render paragraph field #} |
| 65 | {{ content.field_content }} |
| 66 | |
| 67 | {# Iterate paragraphs #} |
| 68 | {% for item in content.field_content['#items'] %} |
| 69 | {{ item.entity.field_text.value }} |
| 70 | {% endfor %} |
| 71 | ``` |
| 72 | |
| 73 | ## Common Bundle Check Pattern |
| 74 | |
| 75 | ```php |
| 76 | foreach ($node->get('field_content')->referencedEntities() as $paragraph) { |
| 77 | /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */ |
| 78 | switch ($paragraph->bundle()) { |
| 79 | case 'text_block': |
| 80 | // Handle text block. |
| 81 | break; |
| 82 | case 'image_block': |
| 83 | // Handle image block. |
| 84 | break; |
| 85 | } |
| 86 | } |
| 87 | ``` |