11

I want to change the view mode of node programmatically. I used hook_preprocess_node(&$vars) and set the view mode:

function moduleName_preprocess_node(&$vars) {
      // if conditions to apply particular view mode
      $vars['view_mode'] = 'teaser';
      $vars['elements']['#view_mode'] = 'teaser';
}

But this is not working as expected. Am I missing something here?

1

2 Answers 2

13

Altering the view mode in the preprocess function is doing it too late.
The correct way to alter the view module is implementing hook_entity_view_mode_alter(), which is called before the entity content is rendered. For example, in node_view(), that hook is invoked from node_build_content(), which is the first function called from node_view().

  if (!isset($langcode)) {
    $langcode = $GLOBALS['language_content']->language;
  }

  // Populate $node->content with a render() array.
  node_build_content($node, $view_mode, $langcode);
1
  • 4
    Thank you. Please note that this hook requires drupal >= 7.17
    – cissharp
    Commented Feb 4, 2013 at 21:46
6

If you need to just change it for certain pages, I'd suggest View Mode Page. It's pretty handy and simple to use.

1
  • Thank you. But I do have different scenario. I want to use different view mode for nodes with same content type. I want to alter the view mode on the taxonomy I used in the node. I mean the nodes will have same URL patterns.
    – cissharp
    Commented Feb 4, 2013 at 17:22

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.