Search code examples
phpdrupaldrupal-7drupal-modulesdrupal-theming

Customizing file link in Drupal7 template


I'm creating a custom layout (node--article.tpl.php) for a custom content type based on the Article type supplied in the base Drupal7 install. All I've added is a file attachment field for a PDF file.

I want to have a link in the rendered page that says something like ("PDF Version"). I've created a template file for that content type and it's working ok. I've used the print render($content['field_pdf']); code snippet to display the file link. It shows as the file's name as a link to the file with a PDF icon beside it. Almost perfect!

I just need to change the file's name to the static string "PDF Version".

Thanks in advance!


Solution

  • Use hook_node_view_alter()

    function yourmodule_node_view_alter(&$build)
    {
        $node = $build['#node'];
        if($node->type == "article" && isset($build['field_pdf']['#items']))
        {
            $build['field_pdf']['#items'][0]['#file']->filename = t('PDF Version');
        }
    }
    

    OR

    function yourmodule_node_view_alter(&$build)
    {
        $node = $build['#node'];
        if($node->type == "article" && isset($build['field_pdf']['#items']))
        {
            hide($build['field_pdf']);
            $build['my_themed_link']['#markup'] = l(t('PDF Version'), file_build_uri($build['field_pdf']['#items'][0]['uri']));
            $build['my_themed_link']['#weight'] = 10;
        }
    }
    

    I haven't tested that yet, hope it works for you.

    Muhammad