18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 4<br />

Preprocess functions<br />

Our theme hook is now given a $node object, but template files expect variables<br />

containing strings or render elements. So we're going to need to transform the $node<br />

object's data into a series of variables. Technically, we could have performed this<br />

business logic directly inside our single_blog_block_view() function, but instead<br />

we're going to do this transformation in a preprocess function.<br />

That's actually the purpose of the preprocess function: to transform raw data into<br />

variables needed for a theme hook's template or theme function. (Also, recall that<br />

preprocess functions should never query for raw data; the raw data should be<br />

passed as variables.)<br />

Since we own this theme hook, we'll need to define our preprocess function with<br />

a template_ prefix.<br />

/**<br />

* Preprocesses single blog block item variables.<br />

*/<br />

function template_preprocess_single_blog_block_item(&$variables) {<br />

$node = $variables['node'];<br />

To make it easier to access all the object properties of our node variable, we're going<br />

to first create a $node local variable which we'll use inside the preprocess function:<br />

// Create a renderable array for the title.<br />

$variables['title'] = array(<br />

'#type' => 'link',<br />

'#title' => $node->title,<br />

'#href' => 'node/' . $node->nid,<br />

);<br />

Next we'll create the $title variable as a render element; it is identical to what we<br />

saw in the second version of our module:<br />

// Format the creation date of the node.<br />

$variables['created'] = $node->created;<br />

$variables['date'] = format_date($node->created, 'custom',<br />

'F d, Y');<br />

Date timestamps don't make very good render elements, so we'll just create two<br />

variables, one with the raw, unformatted date value and one with formatted date:<br />

// Load the account object with the node's creator and store<br />

// in a variable for themer convenience.<br />

$variables['user'] = user_load($node->uid);<br />

[ 109 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!