Skip to main content

Change picture mapping conditionally according to field value drupal 7

Hi Drupalars,

Recently i got a task 

"to provide an option in paragraph item to display a image grid 3 by 3 or 2 by 2"
3 by 3 grid




2 by 2 grid

Adding conditional classes was fairly easy for each case , which is achieved by following code

 /**  
  * Implements hook_preprocess_entity().  
  */  
 function YOURTHEME_preprocess_entity(&$variables) {  
 if (!empty($variables['elements']['#entity']->field_show_50_50)) {  
    if ($variables['elements']['#entity']->field_show_50_50['und'][0]['value'] == "1") {  
     $variables['classes_array'][] = 'show-50-50';  
    };  
   }  
      if (!empty($variables['elements']['#entity']->field_show_100)) {  
    if ($variables['elements']['#entity']->field_show_100['und'][0]['value'] == "1") {  
     $variables['classes_array'][] = 'show-100';  
    };  
   }  
 }  

By doing , new problem arises about image aspect ratio getting distrupted.

As i was using Picture module for creating different version of image for each breakpoint for our responsive web site.

So i had to also change the picture mapping of image. So i created two new picture mapping and applied conditionally by using following code

 function YOURTHEME_field_display_paragraphs_item_alter(&$display, $context){  
  $entity = $context['entity'];  
  if($context['field']['field_name'] == 'field_image' && $context['entity']->bundle == 'voices_tile'){  
  $hostEntity = $context['entity']->hostEntity(); // image field inside a parent paragraph 
  if($hostEntity->field_show_100[LANGUAGE_NONE][0]['value'] == 1){  
  $display['settings']['picture_mapping'] = 'voice_picture_mappping_1368x455_';   
  }  
  if($hostEntity->field_show_50_50[LANGUAGE_NONE][0]['value'] == 1){  
  $display['settings']['picture_mapping'] = 'voice_images_50_50';   
  }  
  }  
 }  











Comments