Practical Drupal Development #1 "template_" preprocess functions


We start a new series on Drupal Development. Throughout this series we'll be posing practical issues to be solved by using all those development tools provided by Drupal (themes, modules, API...). This time we are going to cover the following issue:

Issue to be solved

After installing Drupal, you're reported to customize the submission information located beneath the title of each node.

If you were told to solve this issue without any knowledge of the Drupal API, then you would be tempted to edit the code off the node.tpl.php file. Although that approach would eventually work for you, that's not how Drupal works, or, in other words, that's not the Drupal way.

A Drupal theme is normally made up of CSS, JavaScripts, images, template files, a .info file and a template.php file. The template.php file is intended for the theme to contain all of the PHP functions and is automatically loaded when the theme is initialized (the template.php file is analogous to a module's .module file). This is the file to be edited in order for you to customize the submission information.

In addition, since a template file should be limited to just print out PHP variables, any processing you need to do to those variables must be done by using a template_preprocess function (this kind of function was added to Drupal in version 7). That's what you'll be doing for the theme hook node, like this:


Notice the ampersand symbol & preceding $variables. This symbol is used by PHP to set up a reference to the original variable. The template_ prefix tells Drupal's theme system that this preprocess function is the primary preprocessor for the theme's hook variables.

So here is the code to be pasted into template.php to customize the submission information. As an example: since the user name submitting the nodes is always the same on this site, it makes no sense to display it over and over again. Let's remove it!

 * This preprocess function is the primary preprocessor for theme hook node.
function cti_flex_preprocess_node(&$variables) {

  $node = $variables['node'];

  $variables['date'] =
   format_date($node->created, $type = 'custom', $format = 'D, m/d/Y');

  $variables['submitted'] =
   t('Submitted on !datetime', array('!datetime' => $variables['date']));


Notice that cti_flex is the name of the current theme. For further information about template_preprocess_node, please click on this link.