Adding a class to default images in Drupal 8

December 20, 2016

As with many sites, images are an important part of the design for my art gallery listings site, The Gallery Guide. The tricky part is that the site is full of user-generated content, so not all of the listings have images attached.

Where there isn’t an image, we use a placeholder - partly for our ‘tiles’ design pattern, but also because the image is an integral part of the design for an individual listing on large screens. On a small screen, this placeholder image takes up a lot of space, and doesn’t add much, so I wanted to hide it at a certain breakpoint.

It took me a while to get my head around how to get into the right place to be able to do this in Drupal 8, following my old standby of sprinkling my code with dpm statements (replaced in D8 with kint). I should really have cracked out XDebug, but it does slow things down quite a bit, and I was too lazy to uncomment a few lines in php.ini. In this case it would have definitely made sense, because the kint output was so large that it slowed my browser down to a crawl - probably because I hadn’t previously read this DrupalEasy article.

Having looked at the variables in scope inside template_preprocess_field, I saw that the relevant object was an instance of the class FileFieldItemList, which extends EntityReferenceFieldItemList. This is a good example of where a good IDE like PHPStorm can really help - having found the class, I could quickly navigate to its parent, and see its methods - in this case the relevant one was referencedEntities():

/**
 * Implements hook_preprocess_field().
 */
function mytheme_preprocess_field(&$variables, $hook) {
  switch ($variables['element']['#field_name']) {
    // Machine name of the field
    case 'field_image':
      // If this is the default image, add a class.
      $images = $variables['element']['#items']->referencedEntities();
      if (empty($images)) {
        $variables['attributes']['class'][] = 'image__default';
      }
      break;
  }
}

Once that class has been added, we can apply CSS to it - in my case it’s in a SASS mixin that gets applied to a few different elements:


@mixin image-main {
  &.image__default img {
    @include breakpoint($mobile-only) {
      display: none;
    }
  }
}

Here’s an example on the live site of a listing with no image uploaded, and by comparison, a listing with an image - as you can see, the design wouldn’t work on large screens if the placeholder image wasn’t there, but on small screens the placeholder just takes up space without giving the user anything worth looking at.

The solution isn’t perfect, because the browser will still download the image, even if it’s set to display: none, as Tim Kadlec wrote about a while ago. But it’ll do for a side project…