Tuesday, January 10, 2017

Add a custom view mode to an entity

Drupal 7 offers a mechanism to render entities which called view mode. For example you can set up how your entity will look as a full page or as a teaser. By default Drupal provides only two modes for node entity (default and teaser) and one default mode for taxonomy term and user entities. But you can easily add your custom view mode.

First option is setup display suite module. It's powerfull and provides a lot of features like a layout for entity that can be set up from admin UI. But if you need just to add a view mode to an entity and don't need any other functionality you can do it manually.

In this example we will add a new view mode to a node entity:
<?php

/**
 * Implements hook_entity_info_alter().
 */
function module_entity_info_alter(&$entity_info) {
  $entity_info['node']['view modes']['custom_view_mode'] = [
    'label' => t('Custom view mode title'),
    // Use default display settings from `default` view mode.
    // It means that all fields labels settings and fields
    // formatters settings will be exactly the same as in
    // `default` view mode.
    'custom settings' => FALSE,
  ];
}
Now clear the cache and you will get a new view mode.








Basically that's all. You can set up fields formatters, weights and etc. But you might want to assign a specific template for nodes per view mode. Well it's not hard to do. Just define a hook_preprocess_node in theme's template.php file:
<?php

/**
 * Implements theme_preprocess_node().
 */
function theme_preprocess_node(&$variables) {
  $variables['theme_hook_suggestions'][] = 'node__' . $variables['type'] . '__' . $variables['view_mode'];
}
Then define node--node-type--view-mode.tpl.php template in your theme folder and provide needed markup there. I suggest to get the default markup from node.tpl.php file and modify it. Clear the cache once again and you will get a rendered through defined template node.

Key notes:

No comments:

Post a Comment