1

I am trying to adapt the following Drupal 7 code to Drupal 8, in order to set a different image style to every image in a view:

// Assigns a random style name to each image
function <MODULE_NAME>_views_pre_render(&$view)
{    
  if($view->name == 'SOME VIEW') 
  {
    $styles = array('thumbnail', 'medium', 'large');
    foreach($view->result as &$result) 
    { 
      $result->field_field_image[0]['rendered']['#image_style'] = $styles[array_rand($styles)];        
    } 
  }
}

Right now I have:

function <MODULE_NAME>_views_pre_render(ViewExecutable $view)
{    
  if($view->id() == 'SOME VIEW') 
  {
    $styles = array('thumbnail', 'medium', 'large');
    foreach($view->result as &$result) 
    { 
      $image = $result->_entity->get("field_media_image");
      $image->SOME_FUNCTION('#style_name') = $styles[array_rand($styles)];        
    } 
  }
}

However, I can't figure out what SOME_FUNCTION would be -- There does not appear to be any way to access the render array from an ImageItem object.

1 Answer 1

2

I gave up on hook_views_pre_render and wound up meeting my requirements with template_preprocess_image_formatter as follows:

function <TEMPLATE_NAME>_preprocess_image_formatter(&$variables) {
  $styles = array('thumbnail', 'medium', 'large');
  if ($variables['image']['#style_name'] === 'medium') {
    $variables['image']['#style_name'] = $styles[array_rand($styles)];
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.