Different Image Presets depending on the number of images in a Drupal multi-field

The other day I had the task to display the image of a multi-upload image field with a bigger image style if there was only one image uploaded.

I solved it by using a combination of the following modules:

In the display settings of my content type I created a duplicate of my image gallery field using Display Suite‘s Dynamic Field. (You could also achieve this by using Display Suite’s Code Field or creating a Computed Field that just outputs the value of your gallery field.)

For that new instance of my gallery field I set the desired bigger image style and the instruction to only show the first image if there are multiple.

Now I had the small gallery thumbnails and the big image being shown on node view.

Detect the number of images uploaded to a multi value field

To count the number of images uploaded to the gallery field I created a new Computed Field that I named field_detect_single_image with the following Computed code:

if(isset($entity->field_bildergalerie['und'])) {
  $image_counter = count($entity->field_bildergalerie['und']);
  if($image_counter == "1") {
     $entity_field[0]['value'] = 'single-image';

Note that field_bildergalerie is the name of my original gallery field, so change it accordingly.

This code simply counts the number of array elements inside my gallery field and saves it to $image_counter. If $image_counter has the value 1it simpy saves the string single-image to the computed field. This is the value we will now check agains using Field formatter conditions

The Display Code is just left with the default value:

$display_output = $entity_field_item['value'];

Note: you’ll have to re-save all existing nodes for the computed field’s code to run. I recommend using Views Bulk Operations if you have lots of nodes to re-save.

Checking field values to conditionally hide fields using Field formatter conditions

Now we can go back to the display settings of our node and add conditions to both our original gallery field and the mirrored one with the bigger image style.

Hide the gallery field when there’s only one image uploaded

Simply open the Conditons fieldset for the original instance of the gallery field and add the following conditon:

  1. Hide when target field does not contain a string
  2. Select target field: Detect Single Gallery Image (e.G. the name of your computed field)
  3. Enter target string: single-image

Hide the big single image when there’s more than one image uploaded

On the copy of our field instance which shows the bigger image simply add the reverse condition (Hide when target field does not contain a string):

That’s basically it.

Leave a Reply