Sunday, September 18, 2011

Showing the first image in the teaser for a Drupal 7 Image Field with multiple values

A Drupal 7 image field that is set to contain multiple values (multiple images), will display all of the images in both the teaser and full node view. There is no option when creating a node which contains this image field to only show the first image in the teaser. However, you can adjust the teaser to only display the first image with Drupal 7 field-level templating.

In order do this globally for a field named "field_image", you can use the following code in a template file named "field--field_image.tpl.php". 

<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>> 
<?php if (!$label_hidden) : ?> 
<div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;</div> 
<?php endif; ?> 
<div class="field-items"<?php print $content_attributes; ?>> 
<?php if ($element['#view_mode']=="teaser") { ?> 
<div class="field-item even"<?php print $item_attributes[0]; ?>><?php print render($items[0]); ?></div> 
<?php } else { ?> 
<?php foreach ($items as $delta => $item) : ?> 
<div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?></div> 
<?php endforeach; ?> 
<?php } ?> 
</div> 
</div>

It is generally a good idea to override the field.tpl.php. Note that inside the field.tpl.php in modules/field/theme, there is the following comment:

THIS FILE IS NOT USED AND IS HERE AS A STARTING POINT FOR CUSTOMIZATION ONLY.
See http://api.drupal.org/api/function/theme_field/7 for details.
After copying this file to your theme's folder and customizing it, remove this HTML comment.

Showing the first image of multi-value image field using the Views module

The views module includes an option for which values to display of multi-value fields. This option is called "MULTIPLE FIELD SETTINGS". In order to display only the first value, just change the corresponding text-field to Display 1 value starting from 0 (or starting from any other item you want).



3 comments:

Anonymous said...

Thanks a lot

Unknown said...

where i must put that file (field--field_image.tpl.php) ?

Anonymous said...

Thank you for this detailed article. It was extremely useful and a simple solution to a frustrating problem.

@bansuk You need to put it in your theme's 'tpl' folder. For example if your theme is called 'fancy' then you save the file into: mysite/sites/all/themes/fancy/tpl