Drupal 7: How to add a custom node view and force a node template to use it

  • Posted on: 15 October 2012
  • By: shivanj

This is a small Drupal 7 tip if you wanted to create a custom node view and force a node template to use this custom node view.

Use case

Let's say you are creating a custom node template for a node of type "grades". You may need to show/hide specific fields in your content type for your Grades template. (This is just an example but you can use this tip in various ways).

The Steps

    You can create a new view mode by putting this code into your custom module:

  1. /**
    * Implements hook_entity_info_alter().
    */
    function MYMODULE_entity_info_alter(&$entity_info) {
    $entity_info['node']['view modes']['custom_teaser'] = array(
    'label' => t('Your Custom Teaser'),
    'custom settings' => TRUE,
    );
    }
  2. Then go to Manage Displays in your content type and set which fields you want to show/hide in the "Your Custom Teaser" view mode.
  3. Now you have to force the viewing of your node to use this custom node view "Your Cusom Teaser". Put this code into your custom module:


    function MYMODULE_preprocess_node(&$variables) {
    if ($variables['elements']['#view_mode'] == 'custom_teaser') {
    $variables['theme_hook_suggestions'][] = "node__grades";
    }
    }

    This will force the viewing of your custom content type "grades" to use grade.tpl.php

Further Reading

Here is how you would make a View use your custom node view for Drupal 7.

Comments