0

Im trying to use function theme_preprocess_field to get the file path of a file field.

I have tried different variations of below.

  function mytheme_preprocess_field(&$variables) {
    if ($variables['element']['#field_name'] == 'my_file_field') {
      $uri = \Drupal\file\Entity\File::load($variables['items'][0]['content']['#item']->getValue())->getFileUri();
      $variables['my_file_field_path'] = $uri;
    }
  }

In my instance it says value null, but it isn't.

How can I get the file path of my_file_field? Thanks

1 Answer 1

0

In a template don't use a content variable to get references to objects. This is what the template is rendering. The structure depends on the field formatter and its configuration. Use it only if you want to change this rendered output.

For object references use element(s), unless you find a dedicated variable in the Twig doc block.

function mytheme_preprocess_field(&$variables) {
  $element = $variables['element'];
  if ($element['#field_name'] == 'my_file_field') {
    $items = $element['#items'];
    if (!$items->isEmpty()) {
      $file = $items[0]->entity;
      if ($file instanceof \Drupal\file\Entity\File) {
        $uri = $file->getFileUri();
      }
    }
  }
}

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.