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?


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);
  • 4
    Thank you. Please note that this hook requires drupal >= 7.17
    – cissharp
    Feb 4 '13 at 21:46

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

  • 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
    Feb 4 '13 at 17:22

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.