Skip to content

Instantly share code, notes, and snippets.

@cesarmiquel
Forked from swichers/d7-add-entity-view-mode.md
Last active January 5, 2016 05:22
Show Gist options
  • Save cesarmiquel/7440049861edbbc7a64d to your computer and use it in GitHub Desktop.
Save cesarmiquel/7440049861edbbc7a64d to your computer and use it in GitHub Desktop.
Drupal 7 - Programmatically add view mode to entity

In a module file:

This will enable an additional view mode for use on the specified entity type(s). Many examples will show the custom settings here being set to TRUE. If TRUE is used then that view mode is added to all entities of the specified type regardless of if it should be on the bundle or not.

/**
 * Implements hook_entity_info_alter().
 */
function HOOK_entity_info_alter(&$entity_info) {

  $entity_info['node']['view modes'] += array(
    'view_mode_machine_name' => array(
      'label' => t('View mode display name'),
      'custom settings' => FALSE,
    ),
  );

  return $entity_info;
}

Where "view_mode_machine_name" is the machine name of the view mode you want to add (ex: sidebar).

In a hook_update(), hook_install(), or hook_enable():

This code will enable the view mode for a specific bundle. This is optional if the view mode should be disabled by default.

  $settings = field_bundle_settings('node', 'article');
  $settings['view_modes']['view_mode_machine_name']['custom_settings'] = TRUE;
  field_bundle_settings('node', 'article', $settings);

Where "node" is the entity type (node, file, taxonomy_term, etc.).

Where "article" is the bundle (node type).

Where "view_mode_machine_name" is the machine name above (ex: sidebar).

To add a template suggestion for your view mode:

/**
 * Implements hook_preprocess_node().
 * Template file suggestion for the previously generated view mode
 * e.g.: node--article--view-mode-machine-name.tpl.php
 */
function HOOK_preprocess_node(&$vars) {
  if($vars['view_mode'] == 'view_mode_machine_name') {
    $vars['theme_hook_suggestions'][] = 'node__' . $vars['type'] . '__view_mode_machine_name';
  }
} 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment