Adding classes to the Drupal image_formatter link

So you are using Drupal, and you are outputting an image field from a node to the screen.  You have it set up so that the display is using an image_style to generate a thumbnail, and you are linking to the full size image.  All great, except you want an additional class on the link….

You could override the field template so that it has the field hard coded.  Seems like a bit of hard work, and massively redundant since all you want is a single (or couple of) class(es) on the link (as you’re using a Bootstrap based theme and want to add the thumbnail class)

Preprocess this

Enter theme_preprocess_field(), which is called before any field is rendered, and is your friend.

First thing to do is target the field that you are looking to modify, which is done like this

function THEME-NAME_preprocess_field(&$variables, $hook) {
  if ($variables['element']['#field_name'] == 'field_FIELD-NAME') {
    ...
  }
}

Next thing is to add the class to the link.  The image formatter uses items from the #path array to construct and link, and makes use of the l() function, so we need to bare that in mind when we are adding classes.  The option array with the #path array gets passed into the l function as the options parameter.

The final code looks like this.

function THEME-NAME_preprocess_field(&$variables, $hook) {
  if ($variables['element']['#field_name'] == 'field_FIELD-NAME') {
    foreach ($variables['item'] as &$item) {
      $item['#path']['options']['attributes']['class'] = array(
        'my-class',
      );
    }
  }
}

So there we have it, our class is added to the link, in just a few lines of code, without overriding a template that could easily get stale or hard to maintain.


Posted

in

by

Comments

Leave a Reply