Question

I would like to create "related item" with paragraphs.

I have 2 content type using paragraph field. This paragraph field has different options, like "quotes, related items, slider" etc.

I want to get some fields from "related item". "Related item" field is a "Entity reference".

Inside paragraphs type I have one called "related item" related item

Inside this I have a field type "entity reference"

I have different pages where I can add this paragraph and choose the entity.

I want to get specific fields from this entity type.

I know I can acomplish this with a view, relationship and contextual filters, but I don't how to do this with a paragraph or if it is possible.

Was it helpful?

Solution

You may have to jump through several hoops to get the data from the entity reference field.

  // Query entity types  
  $query = \Drupal::entityQuery('node');
  $query->condition('status', 1);
  $query->condition('type', 'your_content_type');
  $entity_ids = $query->execute();

  // Query paragraph types
  $paragraph = \Drupal::entityQuery('paragraph');
  $paragraph->condition('status', 1);
  $paragraph->condition('type', 'paragraph_type');
  $paragraph_ids = $paragraph->execute();

  // Loop through entity IDs
  $paragraph_output = array();
  foreach($paragraph_ids as $pid){

    // Load each paragraph
    $paragraph = Paragraph::load($pid);

    // Load each entity reference field
    $entity_id = $paragraph->get('field_entity_identifier')->getValue();

    // Get entity parent Node ID
    $parent_node = \Drupal::entityManager()->getStorage('node')->load($parent_id[0]['value']);

    // You'll need to insert another foreach loop here drilling down further into the node that is being referenced.

  }

First you have to loop through the content types. Then you have to look to see if those paragraphs are set and have data. Then you loop through the paragraph types data and get the nodes they reference. Then you have to loop referenced nodes.

It's not an exact solution, but it's how I load data in modules and create my own API endpoints for some fairly heavy frontend javascript applications.

Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top