Drupal - How to load paragraph entity on node object?

$paragraph = $node->field_paragraph->getValue();
// Loop through the result set.
foreach ( $paragraph as $element ) {
  $p = \Drupal\paragraphs\Entity\Paragraph::load( $element['target_id'] );
  $text = $p->field_name->getValue();
}

Just replace get() with field name directly :

$node  = \Drupal\node\Entity\Node::load(1);
$paras = $node->field_paragraph->referencedEntities();

This method will work a bit faster.

// Get data from field.
if ($paragraph_field_items = $node->get('field_paragraph')->getValue()) {
  // Get storage. It very useful for loading a small number of objects.
  $paragraph_storage = \Drupal::entityTypeManager()->getStorage('paragraph');
  // Collect paragraph field's ids.
  $ids = array_column($paragraph_field_items, 'target_id');
  // Load all paragraph objects.
  $paragraphs_objects = $paragraph_storage->loadMultiple($ids);
  /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
  foreach ($paragraphs_objects as $paragraph) {
    // Get field from the paragraph.
    $text = $paragraph->get('field_title')->value;
    // Do something with $text...
  }
}

You can also easily implement this code in some method in your custom service with @entity_type.manager argument and load storage for nodes and paragraphs in __construct().

Tags:

8

Paragraphs