Rick
Rick

Reputation: 1569

Read values of entity reference within another entity reference in Paragraph preprocess - D9

I have a content type that has a Paragraph entity reference field named "Grants". This "Grants" paragraph field has another paragraph entity reference field names "contacts". So the entity references are nested as :

Awards content type ---->(refers)--->Grants paragraph field--->(refers)--->Contacts paragraph field

I am trying to read the contacts reference fields in hook_preprocess_paragraph method and I cannot do that:

    function mytheme_preprocess_paragraph(array &$variables) {
      $pval = $variables['elements']['#paragraph'];
      $paragraph = $pval->field_grant_contacts->getValue();
      foreach ( $paragraph as $element ) {
      $p = \Drupal\paragraphs\Entity\Paragraph::load( $element['target_id'] );
      $text = $p->field_contact_name->getValue();
     }
  dd($text);
    }

I am trying to reference the primary field - field_grant_contact. Through that I'm trying to read field_contact_name and the getValue method returns null. Any help on how to read nested entity reference fields?

Upvotes: 1

Views: 3142

Answers (1)

milkovsky
milkovsky

Reputation: 8862

There is a helpful method Entity::referencedEntities to get relations. Also to get text value use $p->field_contact_name->value.

In your case try the next code:

function mytheme_preprocess_paragraph(array &$variables) {
  /** @var \Drupal\paragraphs\ParagraphInterface $paragraph */
  $paragraph = $variables['elements']['#paragraph'];
  /** @var \Drupal\paragraphs\ParagraphInterface[] $contacts */
  $contacts = $paragraph->field_grant_contacts->referencedEntities();
  foreach ($contacts as $contact) {
    $text = $contact->field_contact_name->value;
    var_dump($text);
  }
}

Upvotes: 1

Related Questions