View-related hooks.

Last updated on
14 October 2016

If your module makes use of entity_view(), add the following view-related hooks:

/**
 * Act on a {ENTITY} that is being assembled before rendering.
 *
 * @param ${ENTITY}
 *   The {ENTITY} entity.
 * @param $view_mode
 *   The view mode the {ENTITY} is rendered in.
 * @param $langcode
 *   The language code used for rendering.
 *
 * The module may add elements to ${ENTITY}->content prior to rendering. The
 * structure of ${ENTITY}->content is a renderable array as expected by
 * drupal_render().
 *
 * @see hook_entity_prepare_view()
 * @see hook_entity_view()
 */
function hook_{ENTITY_ID}_view(${ENTITY}, $view_mode, $langcode) {
  ${ENTITY}->content['my_additional_field'] = array(
    '#markup' => $additional_field,
    '#weight' => 10,
    '#theme' => 'mymodule_my_additional_field',
  );
}

/**
 * Alter the results of entity_view() for {ENTITY}s.
 *
 * @param $build
 *   A renderable array representing the {ENTITY} content.
 *
 * This hook is called after the content has been assembled in a structured
 * array and may be used for doing processing which requires that the complete
 * {ENTITY} content structure has been built.
 *
 * If the module wishes to act on the rendered HTML of the {ENTITY} rather than
 * the structured content array, it may use this hook to add a #post_render
 * callback. Alternatively, it could also implement hook_preprocess_{ENTITY}().
 * See drupal_render() and theme() documentation respectively for details.
 *
 * @see hook_entity_view_alter()
 */
function hook_{ENTITY_ID}_view_alter($build) {
  if ($build['#view_mode'] == 'full' && isset($build['an_additional_field'])) {
    // Change its weight.
    $build['an_additional_field']['#weight'] = -10;

    // Add a #post_render callback to act on the rendered HTML of the entity.
    $build['#post_render'][] = 'my_module_post_render';
  }
}