Theme File Link in Drupal 7

By shane
Tue, 2012-05-29 11:50

Share with Others

For consistency's sake it is always a good idea to output any file download links the same way throughout any website. If you are using file uploads attached to nodes on your Drupal 7 website, this is generally taken care of for you. You will notice that all file links are displayed with a consistent icon set (which can be overridden), as well as a consistent link. This applies to all node pages and any views that contain the downloadable files.

What happens if you want to display your own download link to a file outside of views or on the node page. In my case I had to create a complex listing of nodes. In this (very rare) case, views could not handle what was needed so I had to build my own display.

I needed to output the files in a similar way to views. It turns out this is very simple. Just call the file_link theme function.

theme('file_link', array('file' => $file));

The $file variable needs to be a file object. This can be retrieved in a few different ways. If you have a fully loaded node object (as I did), you can output the field directly (thanks to Greg in the comments and for showing me this better approach). Simply replace the 'field_my_file_upload' with the name of your file field:

field_view_field('node', $node, 'field_my_file_upload');

If you know the file id of the file, you can use file_load function from the core file module. Note: replace $fid with the id of the file you want to display for download.

theme('file_link', array('file' => file_load($fid)));

Until next time...