Drupal 7 Theming Tip: Any Link on an Image Field with Drupal 7


[Dec. 8,2012 - Thanks to Blair Wadman for  noticing that WordPress ate my - - and turned them into en-dashes, thus confusing anyone reading this!]

I’m moving Clutter Puppy - Daily Clutter Tips from static HTML to Drupal 7, but there are quite a few problems I’m running into with theming for Drupal 7, mostly because the documentation is pretty unorganized for Drupal 7 theming. I’m pretty familiar with theming nodes and fields for Drupal 6 with CCK - now that CCK has moved into core for Drupal 7, the API has changed.

In my case, I’m trying to do something simple - on my node, I have two fields that I’d like to use together - “field_url”, which is a text field, and “field_pictures”, which holds an unlimited number of Drupal 7 Image fields. I’d like each image to link to the URL in field_url - that’s not the node URL, it’s just an arbitrary URL that gets entered at content creation.

One thing that really frustrates me about Drupal is how easy this would be with other web application frameworks. Most of them, you’d simply add a foreach loop to your template, and write out the a href and img tags with tip.url and tip.imageUrl. Done!

With Drupal, things get more complicated and the documentation gets horrible as soon as you want to change the default rendering for a Drupal node. With Drupal 7 to do this simple task, you’ll need to modify node.tpl.php, and create a field- -field_pictures.tpl.php template.

In node.tpl.php, put:

<?php print render($content\['field\_pictures'\]); ?>

where you want the pictures - this by itself isn’t too bad, but because every field wants to render itself, you’ll need to replace the default field rendering template for field_pictures. Inside of field- -field_pictures.tpl.php, put:

<ul>

<?php foreach ($items as $delta => $item) : ?>

<li><a target="\_blank" 

href="<?php print $element\['#object'\]->field\_url\['und'\]\[0\]\['value'\]; 

?>"><?php print render($item); ?></a></li>

<?php endforeach; ?>

</ul>

for a nice unordered list that you can plug into a jQuery plugin, for instance.

The key here was to use the un-Googleable $element[‘#object’] to represent the parent node, and then to retrieve the field_url’s value from the node.

If there’s a better way to do this, I’d love to hear it - the D7 theming guide seems to be missing a discussion of the new D7 fields and how to theme them.