Skip to main content

One Image Field, Multiple Aspect Ratios: Part 2

Jun 23 '17

Sometimes, content editors need to be able to choose between various image sizes, but we may still want to limit them to a predefined set of choices. I wrote previously about how to do this with a select field and some CSS, which works well for small assets and SVGs. But what if we have larger assets and want to leverage the power of Drupal's image styles, or better yet, responsive images styles? 

First, set up whatever responsive image styles you'd like available to you. (Not sure how to do that?) In this case, I made myself one called featured_image_portrait and one called featured_image_landscape. You can make as many as you'd like, and name them anything.

I gave my content type two fields: a basic image field called field_featured_img and a list (text) field called field_img_orientation with the following options:


On the content type's "Manage display" tab, set the list field's format to "Key" and the image's to "Responsive image" - it is important to set the image to responsive image and choose a default so that we can change the default value with a preprocess function later.

A screenshot of "manage display" configuration.

Now, we use a simple preprocess function to test for the value of the orientation field and adjust the style of the image field if necessary. Below, I only test for "portrait," because I set landscape as the default above.

function your_theme_slug_preprocess_node(&$variables) {
  if ($variables['node']->getType() == 'your_content_type') {
    if ($variables['content']['field_img_orientation'][0]['#markup'] === 'portrait') {
      $variables['content']['field_featured_img'][0]['#responsive_image_style_id'] = 'featured_image_portrait';

That's it! Adjust as necessary if you wish to use more image style options or limit by display mode.

P.S: I'll be talking more about wrangling images in Drupal 8 at Drupal GovCon. Come see me there!