1

I'd like to programmatically change an image style during hook_node_view(), and I thought this would be relatively straightforward like so:

/**
 * Implements hook_node_view()
 */
function example_node_view($node, $view_mode, $langcode) {

  if (example_ok()) {
    $node->content['field_image'][0]['#image_style'] = 'new_image_style';
  }

}

Unfortunately this does not work. I'm aware of the picture and breakpoints modules, and am in fact using them, however there are sometimes when a dynamic decision needs to be made that these modules don't cover.

  • You could also have a look at display suite and create multiple view-modes for your nodes. Then you can style the image per view-mode. If that makes sense for your use-case – Neograph734 Apr 27 '16 at 17:10
  • Thank you for the suggestion, this will not be acceptable for this project as I'd hate to turn on a very feature rich/heavy module for something that seems like a single line of code should be able to cover. – tyler.frankenstein Apr 27 '16 at 17:12
3

I hate to answer my own question, but this answer pointed me in the right direction. Here's the hook that worked in this case:

/**
 * Implements hook_preprocess_HOOK().
 */
function example_preprocess_image_style(&$variables) {
  if (example_ok()) {
    $variables['style_name'] = 'new_image_style';  
  }
}

function example_ok() {
  global $user;
  // If the logged in user is bob, everything is ok.
  if ($user->uid && $user->name == 'bob') {
    return TRUE;
  }
  return FALSE;
}
  • 1
    I must agree with example_ok ;) – UltraBob Sep 13 '16 at 1:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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