0

I have a custom content type (we'll call it 'book')... and it has a field (We'll call the field 'category') which is of type Taxonomy Term and which can hold say ten items.

I can load the content programmatically:

$nids = \Drupal::entityQuery('node')->condition('type','custom content type machine name')->execute();

        $nodes =  \Drupal\node\Entity\Node::loadMultiple($nids);

I can then scroll through the items of node using something like

  foreach ($node as $node_item){
      echo $node_item->title
   }

However, how would I output the content of the reference entity 'category' ... say if category has 3 items assigned to it, it would be something like this:

  foreach ($node as $node_item){
      echo $node_item->title,
      echo $node_item->category[0]->target_id,
      echo $node_item->category[1]->target_id,
      echo $node_item->category[2]->target_id,
   }

But, this does not work...

There is the suggestion that $node_item->category has to be loaded as an entity reference but using $node->cateogry->referenceEntities () does not load anything.

Any ideas? Thanks in advance.

2

I think $node_item->category->referencedEntities() is what you want to use.

You have misspelled the method in your question.

 if ($node_item->category->isEmpty() === FALSE) {
    $vars = [];
    // Get referenced entities and add each to array of terms.
    foreach ($node_item->category->referencedEntities() as $term) {
      $vars[] = [
        'name' => $term->label(),
        'phone' => $term->field_phone_number->value,
        'email' => $term->field_email_address->value,
      ];
    }
  }
| improve this answer | |
  • Thanks oknate that did the trick ... thanks for taking the time to help – Mo-ster Oct 30 '17 at 16:59

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.