Drupal Background Image Field Formatter

Posted on Tue, 5/19/2015
2 minutes read

Ever ran into the issue on Drupal where you want the user to create a piece of content, but the image they upload needs to be a background image so you can do something like background-contain? I ran into this issue last week multiple times while building out the new Code Koalas site[^1]. The first couple of times we just created a custom field template that looked like this:

<?php foreach ($items as $delta => $item): ?>
  <div class="project-image" style="background-image: url(<?php print file_create_url(image_style_path('half_page_image', $item['#item']['uri'])); ?>)"></div>
<?php endforeach; ?>

There's nothing wrong with the above approach, but it seemed repetitive to do the same thing over and over again each time we needed this, because of our designer we needed this a lot. That's when I started thinking maybe there was some sort of module creating a new field type, but then I realized it just needed to be a field formatter for the image field. That's when I found the module Background Image Formatter, but that only lets you use that image and attach it to a css selector. That's not what I needed, I needed a div that was the background image. That's when I'd like to say I found the module I really needed, Simple Background image formatter, but I didn't find that module until I have completely recreated that module myself[^2].

The module Simple Background image formatter, is fantastic! It does exactly what I needed, it removes the need for tons of custom field templates.

Once you have the module installed, go to your display settings for your content type, on your image field open the formatter options:

alt text

Once you do that, you'll want to edit the settings to make sure you're adding the classes you like.

alt text

You can choose your image style, whether to output as CSS or an inline style on a div, and put css classes on your div. I also am using Display Suite and I choose expert template mode, and leave it blank. I do this because otherwise this div you're making will be wrapped in another div, and that isn't want I wanted.

Once you do all that here is the final results!

alt text

Now you can make background images a breeze with Simple Background image formatter.

[^1]: Site isn't launched yet, sorry to disappoint. [^2]: I seriously created the exact same module by myself, that guy beat me by one month.