[Drupal] How to implement hook_preprocess_HOOK() function in your custom module?

By | 20th Aug 2015 | 2 min read

As the name suggests, a preprocess function is a precursor to a theme function. It runs first, irrespective of the fact that the theme function can also be implemented as a template (.tpl file) rather than a function. Preprocess functions can be implemented in both modules and themes. However, the preprocess implementations from modules run first, and those by themes run only last.

The purpose of a preprocess function is to prepare variables for the use within a theme function or template which renders the data to the screen, usually wrapped in HTML. With the aid of preprocess function, we can add or modify variables. Though, we can change a variable used in a theme function, it is worth noting that all theme functions does not have complimentary preprocess functions.

Preprocess functions are implemented with the following naming convention.

<?php
  /**
   * Implements template_preprocess_THEMEHOOK().
   */
  function HOOK_preprocess_THEMEHOOK(&$variables) {
  // Changes go here.
  }
?>

The preprocess function can be simply placed in your custom module beginning with the custom module name, followed by' _preprocess_' and the theme hook defined in the hook_theme() function. Finally, pass in the '&$variables' parameter by reference for altering.

/**
 * Implements hook_preprocess_HOOK().
 */
function comment_manager_lite_preprocess_comment_admin_overview(&$variables) {
  if (isset($variables['form']['comments']['#options']) && is_array($variables['form']['comments']['#options'])) {
    foreach (element_children($variables['form']['comments']['#options']) as $key) {
      // wrap two render array elements in a single cell
      $wrapper = array(
        '#type' => 'container',
        '#attributes' => array(
          'class' => array('comment-lite'),
        ),
      );
      $wrapper['comment'] = $variables['form']['comments']['#options'][$key]['subject']['data'];
      $wrapper['comment_edit'] = $variables['form']['comment_edit'][$key];
      $wrapper['comment_edit']['#weight'] = 1; 
      
      $variables['form']['comments']['#options'][$key]['subject']['data'] = $wrapper; 
    }
  }
  else {
    $rows = array(array('data' => t('No comments available.'), 'colspan' => '3'));
  }
   unset($variables['form']['comment_edit']);
}

For more help to implement preprocess functions, please contact us.