Theming the attachments table per node type (Drupal 6)

Filed under 

About a year ago I needed to provide a disclaimer above the file attachments table on a Drupal site. I quickly accomplished by using the theme_upload_attachments() function and altering the output. However, this applied the disclaimer site wide. The client later had a need to display file attachments on different pages without the disclaimer. This article explains how I accomplished this.

Providing the disclaimer was a relatively simple task. I just copied the theme_upload_attachments() function from the upload module (found in the /modules/upload/upload.module file) and pasted it into a new template file called upload_attachments.tpl.php. Then I change the output of the function as needed. In the example below, I’ve added a disclaimer line above the final output of the function.

    <?php
      /**
      *  Themed attachments table
      */
      $header = array(t('Attachment'), t('Size'));
      $rows = array();
      foreach ($files as $file) {
        $file = (object)$file;
        if ($file->list && empty($file->remove)) {
          $href = file_create_url($file->filepath);
          $text = $file->description ? $file->description : $file->filename;
          $rows[] = array(l($text, $href), format_size($file->filesize));
        }
      }
      if (count($rows)) {
        // add disclaimer above file attachment table
        $html = '<p class="disclaimer">Webinars provide... Disclaimer text goes here.</p>';
        $html.= theme('table', $header, $rows, array('id' => 'attachments'));
        print $html;
      }
    ?>

This was an appropriate solution for about a year. However, the site owner recently began adding attachment to other node types and obviously did not want a disclaimer for the Webinars shown above attachments for other node types.

The problem is, the upload_attachements template and preprocess hook are not node aware, so you can’t just add a simple if statement around the disclaimer.

The best solution I’ve found is to use the function menu_get_object to load the current node. Then it is easy to check the type of node being shown. The bottom half of the template file was changed to:

    <?php
      if (count($rows)) {
        $html = '';
        $node = menu_get_object();
        if($node->type == 'event') {
          $html.= '<p class="disclaimer">Webinars provide... Disclaimer text goes here.</p>';
        }
        $html.= theme('table', $header, $rows, array('id' => 'attachments'));
        print $html;
      }
    ?>

While I’m not in love with this solution since it requires another trip to the database, it doesn’t make much of a performance impact on this particular site.