I have a node object with image field named field_image
. When I do
$node
->get('field_image')
->first()
->getValue()
I get array with some properties instead of entity object. The array looks like this:
'target_id' => string '8' (length=1)
'alt' => string '' (length=0)
'title' => string '' (length=0)
'width' => string '587' (length=3)
'height' => string '458' (length=3)
'_loaded' => boolean true
'_accessCacheability' =>
object(Drupal\Core\Cache\CacheableMetadata)[1092]
protected 'cacheContexts' =>
array (size=0)
...
protected 'cacheTags' =>
array (size=0)
...
protected 'cacheMaxAge' => int -1
Do I have to manullay load the file entity using target_id
or there is a way to automatically get referenced entity object from instance of Drupal\image\Plugin\Field\FieldType\ImageItem
?
Why the referenced entity is not accessible via getter? It could be lazy loaded if it's not available immediately.
PHP Fatal error: Call to undefined method Drupal\image\Plugin\Field\FieldType\ImageItem::getTarget()
. However$node->get('imagefield')->referencedEntities()
works thanks to the fact$node->get('imagefield')
returns instance ofEntityReferenceFieldItemList
which implementsreferencedEntities()
method. So your solution is only partial - it works for lists but not for single fields.