Drupal - How to change File field icons (without changing core)?

You can override theme_file_icon in your theme, and specify different icon images. See file_icon_path for reference regarding how core determines which icons to use.

You can also set the "file_icon_directory" variable to the path to your icons, as the file_icon_path function looks for the path in that variable.


Two additional notes on this:

  1. It is not necessary to copy all of the default icon files to your theme directory.
  2. If you are using a custom icon, it must be appropriately named in order for it to be found.

As an example, I had a need to use a custom icon for a .bib (bibtex) file. This type is mapped in file_default_mimetype_mapping(), but it defaults to the default text icon since there isn't an icon specifically defined for that mime type (text/x-bibtex).

I overrode theme_file_icon() in my theme's template.php, but I did it so that the icon path is only modified as needed, and I didn't have to copy the default icons directory to my theme directory:

function mytheme_file_icon($variables) {
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $mime = check_plain($file->filemime);

  if ($mime == 'text/x-bibtex') {
    $icon_directory = drupal_get_path('theme', 'mytheme') . '/images';
  }

  $icon_url = file_icon_url($file, $icon_directory);
  return '<img class="file-icon" alt="" title="' . $mime . '" src="' . $icon_url . '" />';
}

The second thing is that you have to name the icon appropriately. If you just keep the use of file_icon_url(), this code from that function will determine the file name for the icon:

// For a few mimetypes, we can "manually" map to a generic icon.
$generic_mime = (string) file_icon_map($file);
$icon_path = $icon_directory . '/' . $generic_mime . '.png';
if ($generic_mime && file_exists($icon_path)) {
  return $icon_path;
}

So in my case, I needed to name my file text-x-bibtex.png. Of course, if you want to just name it whatever you want (bibtex.png in this case), you could just set the file name manually:

$icon_url = $icon_directory . '/bibtex.png';

Either one will work, but this method allows you to keep the default icons where they are and only tweak things as needed.

Tags:

Files

7