5

I already know I can get an url for field of node this way:

$src = file_create_url($node->get('name_of_image_field')->entity->uri->value);

The problem is, my field name_of_image_field has multiple images. How to access them all?

4

You can try this code:

$img_urls = array();
foreach ($node->field_image as $item) {
  if ($item->entity) {
    $img_urls[] = $item->entity->url();
  }
}

Then all field_image image urls available in $img_urls variable.

4
  • Maybe you should remove the kint() function, since it requires devel, or make a note about that in your answer.
    – No Sssweat
    Sep 5 '16 at 3:26
  • The kint line should be $image_urls[] = $item->entity->url(); than he can do another foreach ($image_urls as $key => $url) {... to get the individual urls.
    – No Sssweat
    Sep 5 '16 at 3:39
  • 2
    Note: method url() have use function file_create_url(). don't use again.
    – MrD
    Sep 5 '16 at 4:46
  • Thank you. That's exactly what I needed. Also up-voted Jaypan answer because I didn't know which one was first.
    – PolGraphic
    Sep 6 '16 at 11:37
4
$srcs = array();
// Loop through the Languages
foreach ($node->field_image as $items) {
  // Loop through each item in each language
  foreach($items as $item) {
    if ($item->entity) {
      // Set the path as the key, to prevent duplicates
      $srcs[$item->entity->url()] = $item->entity->url();
    }
  }
}

$srcs will contain an array web-accessible URLs for every image attached to every language of the node.

2
  • 1
    I don't think is good code. Do do you try see code in method url(). public function url($rel = 'canonical', $options = array()) { return file_create_url($this->getFileUri()); }. file_create_url call 4 time in one statements. Very bad.
    – MrD
    Sep 5 '16 at 4:35
  • You're correct, I've edited it accordingly.
    – Jaypan
    Sep 5 '16 at 6:12
0

Maybe you could use:

$delta = 0;
$file_item_list = $node->field_image;

if ($file_item_list && $file_item_list->offsetExists($delta)) {
$image_url = file_create_url($file_item_list->offsetGet($delta)->get('entity')->getValue()->getFileUri());
}

Check Class FileFieldItemList for more details.

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.