Drupal - Get an image from an article/entity

Didn't see this before.

The shortest way to get the referenced entity for a single-value field is this:

$node->field_image->entity->url()

You can also specify the delta explicitly:

$node->field_image[0]->entity->url()

This works with a lot of ArrayAccess and __get() magic.

See also the great cheat sheet at http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet. and https://www.drupal.org/node/1795854 and the other documentation pages there for more information (still very much work in progress).


What ended up working for me in D8 is:

$imageUrl = $node->get('field_image')->entity->uri->value;

Using kint($node->get('field_image')->entity) and looking through the array was very helpful

enter image description here

Then in my twig file I used:

<img class="top-article-image" src="{{ file_url(imageUrl) }}" />

Tags:

Media

Entities

8