I'm using paragraphs in my content type. I've created a paragraph type and added content. Now I want to load the paragraphs in a foreach. But nothing's showing up. $paras is empty:

$node  = \Drupal\node\Entity\Node::load(1);
$paras = $node->get('field_paragraph')->referencedEntities();
  • You said $paras showing blank. but you didn't show how you printed its value. Is it a NULL value, an empty string, or an empty array? Since you commented with I already done this but your answer is right to the answer, which is showing completely different code, your question gets a little confused, and it's not clear what your aren't able to achieve. – kiamlaluno Sep 16 '17 at 11:23
  • This question asked when I am very new in drupal 8 doing task for learning .I think I do some error in process so that time it show blank .But when i do same now it's working fine. you check here a demo run same code . I just create this for you ,d2log.ply.st/devel/php username :: admin password :: admin – Pankaj Yogi Sep 16 '17 at 12:15
$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();
| improve this answer | |
  • I already done this but your answer is right. – Pankaj Yogi Aug 28 '17 at 9:10
  • 1
    Be careful: this solution doesn't include translations. – ssibal Nov 9 '18 at 8:09
  • Instead of Paragraph::load($tid), we now should use \Drupal::entityManager()->getStorage('paragraph')->load($tid). – JFK Feb 9 '19 at 5:45

Just replace get() with field name directly :

$node  = \Drupal\node\Entity\Node::load(1);
$paras = $node->field_paragraph->referencedEntities();
| improve this answer | |
  • Wow, yes, but why? – leymannx Aug 21 '19 at 11:45

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().

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.