I have the attached array below and need help figuring out how to access the 'entity' attribute that is under the protected "properties" array (see screenshot).

I am using the Viewfield module

Entity Reference - Entity value

background: field_name is an entity reference field. I need to get the EntityReference so that I can call getTarget() to get the EntityAdapter and then call EntityAdapter->getValue().

I have tried the following but they all give errors. The idea is to get the EntityReference which is the 'entity' value. How can i do this?

mytheme_preprocess_viewfield_item(&vars) {

  $element = $vars['element'];
  $results = $element['#content']['#view']->result;

  foreach($results as $row) {
    $entity = $row->_entity
    $offset = $entity->get('field_name')->offsetGet(0)

kint($entity->get($video_field_name)) /* result of screenshot */

    $entityReference = $offset->get('entity') /* failed */
    $entityReference = $offset->getProperties() /* failed */
    $entityReference = $offset->getEntity() /* failed */
    $entityReference = $offset->getValue() /* failed */
  }//end foreach
}//end theme_preprocesss

The error message is: replace getValue() with any of the above

Call to a member function getValue() on null

  • It would greatly help to give specific code how you got the array.
    – GiorgosK
    Dec 16, 2017 at 4:18
  • @GiorgosK i have updated the question. Additionally i added the kint() statement that generates the output. Dec 16, 2017 at 4:34

2 Answers 2


If entity in the foreach loop is not empty you should be able to do

//or perhaps
  • the first version worked for me. I still testing the refencedEntities and if it fails I can provide an update otherwise both seem to work. I have added additional validation to ensure entity is not empty Dec 18, 2017 at 18:43

In case you have an EntityReferenceItem you can get the entity with getEntity()


And if you have an EntityReferenceItemList:

$list = $itemList->get(field_name);
foreach ($list as $item) {
  $entity = $item->getEntity();
// or

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.