Add custom View Mode for entity

22 November 2013 — Written by Mitesh Patel
#Drupal 7

<?php
/**
* Implements hook_entity_info_alter().
*/
function foo_entity_info_alter(&$entity_info) {
$entity_info['node']['view modes']['another_teaser'] = array(
'label' => t('Another teaser'),
'custom settings' => TRUE,
);
$entity_info['profile2']['view modes']['another_teaser'] = array(
'label' => t('Another teaser'),
'custom settings' => TRUE,
);
}
/**
* Implements hook_preprocess_node().
*/
function foo_preprocess_node(&$vars) {
if ($vars['view_mode'] == 'another_teaser') {
$vars['theme_hook_suggestions'][] = 'node__' . $vars['type'] . '__another_teaser';
}
}
/**
* Implements hook_preprocess_entity().
*/
function foo_preprocess_entity(&$vars) {
switch ($vars['entity_type']) {
case 'profile2':
// Use different template
$vars['theme_hook_suggestions'][] = "profile2__{$vars['profile2']->type}__{$vars['view_mode']}";
$function_name = "foo_preprocess_profile2_{$vars['profile2']->type}_{$vars['view_mode']}";
if (function_exists($function_name)) {
$function_name($vars);
}
break;
}
}
view raw foo.module hosted with ❤ by GitHub

That will give template suggestions.

  • node--article--another-teaser.tpl.php
  • profile2--TYPENAME--another-teaser.tpl.php

html goes here.
<?php print $vars['defined_vars']; ?>

Copyright © 2022 Mitesh Patel. Built with Gatsby