0

When rendering a node's links, I would like to show a link to a node's uploaded file instead of the read more link. I tried to replace:

$links['node']['#links']['node-readmore']['url']

with the file's url object, but that just throws the error:

Uncaught PHP Exception Drupal\Core\Entity\Exception\UndefinedLinkTemplateException: "No link template 'canonical' found for the 'file' entity type"

My code so far:

/**
 * Implements hook_node_links_alter().
 */
function mymodule_node_links_alter(array &$links, $entity, array &$context) {

  $entityType = $entity->getType();

  if (isset($links['node']['#links']['node-readmore'])) {
    $readmore =& $links['node']['#links']['node-readmore'];

    if ($entity->hasField('field_data_sheet') &&! $entity->get('field_data_sheet')->isEmpty()) {
      $readmore['title'] = t('Download data sheet');

      $fileValue = $entity->field_data_sheet->getValue();
      $fid = $fileValue[0]['target_id'];
      $file = \Drupal\file\Entity\File::load($fid);

      $readmore['url'] = $file->toUrl(); // throws error

      // doesnt do anything:

      $links['file'] = [
        '#type' => 'link',
        '#title' => 'test',
        '#url' => $file->getFileUri(),
      ];
    }
  }
}
  • try using $readmore['url'] = file_create_url($file->getFileUri()); – No Sssweat Jul 28 '17 at 19:27
  • @NoSssweat this doesnt show the link at all, but hey - at least no fatal error :) – Alex Jul 31 '17 at 7:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.