Drupal 8 Image Field value

3.5k views Asked by At

I'm trying to figure out how to get the path to an image from an entity in Drupal 8. I had thought get()->value would do it, but that just returns a blank string.

I have a test function:

function getValueTest ($profile_id, $field)
{
   $profile_storage = \Drupal::entityManager()->getStorage('profile'); 
   $profile = $profile_storage->load($profile_id);
   if ($profile != null)
   {
      if ($profile->hasField ($field))
      {
         return $profile->get ($field)->value;
      }
   }

   return "No field" . $field;
}

Assume some profile id 3 that has two fields field_first_name and field_mugshot. If I call:

dpm ($this->getValueTest (3, 'field_first_name'));
dpm ($this->getValueTest (3, 'field_mugshot'));

The first call correctly displays the first name in the message area, but the second just gives a blank string. I need a path to the image so I can do some processing on its content.

1

There are 1 answers

1
Rotari Radu On BEST ANSWER

You can use the folowing methods to get the uri or the url:

$entity->get('field_image')->entity->getFileUri();
$entity->get('field_image')->entity->url();

This is because value() method should return the value of the field(aka a fid), field which is an entity reference in this case.