Drupal Tips: How to create a custom view in Drupal 7

| | 2 min read

By default Drupal 7 has two types of views - The Full node view and the Teaser view. This has been the case for all previous versions of Drupal. However if your requirements are different, then you might have to create a custom view that is tailored to meet your specific needs. Check out how to create a simple custom “View mode” for nodes in Drupal 7.

Step1: Create a custom module
Step2: Create an additional view mode -’Grid Pane’ by simply implementing hook_entity_info_alter() in our custom module.

/** 
* Implements hook_entity_info_alter().
*/
function CustomModule_entity_info_alter(&$entity_info) {
  $entity_info['node']['view modes']['grid_pane'] = array(
    'label' => t('Grid Pane'),
    'custom settings' => TRUE,
  );
}

Step3: Now apply some theme and custom layout for the content. We can add a custom node.tpl.php template for this view mode for flexible theming and use standard hook_preprocess_node() function to control the variables available in the template.
To make Drupal use a different .tpl.php file for view mode we need to add a new template suggestion in hook_preprocess_node (). Copy the standard node.tpl.php for the content type you need and name it like “node--article--grid_pane.tpl.php”.

/**
* Implements hook_preprocess_node().
*/
function CustomModule_preprocess_node(&$vars) {
  /*dpm(entity_get_info());*/
  if($vars['view_mode'] == 'grid_pane') {
    $vars['theme_hook_suggestions'][] = 'node__' . $vars['type'] . '__grid_pane';
  }
}

Step4: Install the custom module and we are done. Once we create a new view mode, we can go to Admin->Structure->content types->[Manage Display] page and select which fields to display format and additional options for fields, like which image style to use for image fields etc. For example:

Drupal