Creating dynamic output for an entity in Drupal 7 using hook_entity_view()

Drupal Version
7

If you need to create dynamic output on an entity when it is displayed on your Drupal site you have multiple options. One method that is easy to implement is using hook_entity_view().

You can insert this hook function into your custom module (see creating a custom module for more info).

Example:

<?php
function YOUR_MODULE_NAME_entity_view($entity, $type, $view_mode, $langcode){
 
   if (
$type == 'node' && $view_mode == 'full' && $entity->type == 'article'){
     
$output = 'Custom output value';
     
$entity->content['custom_output'] = array(
             
'#markup' => $output,
             
'#weight' => 99,
        );
    } 
}
?>

Within this function you will have access to the full entity object being viewed on your site as well as the entity type, and its view mode. You can then use these values to target a specific condition. In the above example we're only targeting Nodes of the type 'Article' when being view in full mode. Article teasers will be ignored.

You can then populate your $output variable however you'd like, including using HTML. You may need to adjust the #weight to move this output up and down within the display.

You can also use Drupal forms for your output:

<?php
 
//...
 
$output = drupal_get_form('YOUR_FORM_CALLBACK_NAME);
 $entity->content['
custom_output'] = array(
              '
#markup' => drupal_render($output),
             
'#weight' => 99,
        );
?>

NOTE: Computed Field is a module that provides another way to achieve this. We prefer using a small amount of code within our own module but Computed Field offers a lot of flexibility with an UI.

Author Information

Written by: Shawn Ostermann

Shawn is a Drupal Specialists with over 12 years of experiencing building and developing Drupal websites including custom module development and e-commerce websites.