In Drupal 7 I loaded the node/entity I want with node_load / entity_load and, if necessary, then I took a field with multiple deltas and take the value I wanted with a foreach loop.

In Drupal 8 how can I do the same in a hook?

For example, this loads my first value of a field:

$a_id = $adress->field_a->target_id;

In this case an entity reference field. But there are more target_ids.

So how to take them?

  • 2
    $adress->field_a should be iterable..so foreach ($address->field_a as $item)? – Clive Jan 6 '16 at 16:59
  • Yes indeed, that's correct. I think I need a long time for d8! Tanks a lot! – maen Jan 6 '16 at 18:04
  • 2
    @Clive you should add that as the answer :) You need the points! ;) – Berdir Jan 6 '16 at 18:33
  • @Berdir Shhh I'm trying to let someone else answer it so maybe they get the points...these things are heavy ;) – Clive Jan 7 '16 at 23:55

Entity reference fields have a method called referencedEntities().

Usage example:

$addresses = $entity->get('address');
foreach($addresses->referencedEntities() as $delta => $address) {
  // Do something with the $address entity

P.S. If you only want the field then as @Clive mentioned you can just iterate over $addresses.

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.