2

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 '17 at 4:18
  • @GiorgosK i have updated the question. Additionally i added the kint() statement that generates the output. – usernameabc Dec 16 '17 at 4:34
2

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

$entity->field_name->entity
//or perhaps
$entity->field_name->referencedEntities();
  • 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 – usernameabc Dec 18 '17 at 18:43

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.