In my last article I demonstrated how to extract basic data from field array elements which is ideal for custom node theming. The key to this is using field_get_items. I'll expand upon that by adding in additional Drupal API functions to enhance and format these Field array elements. Building upon the code example from the previous tutorial, let's add a new variable to our preprocess function so that we can render it in node--events.tpl.php representing a custom event content type. The basic preprocess function lives in our theme's template.php file.
Right now all this does is make field_event_image available to extract data from but we need to add what array element we want to theme. From the array of values we printed, there is one called 'Timestamp'. When we printed to see what variables were available, it printed in the node as:
Create the Basic Variable for Preprocessing
Essentially this is the time the image was uploaded. We can create a variable for it in the preprocess function as:
We can then render this in our custom node as:
This will print on the page as:
Add in the API Function
As you can see, it's not a very user friendly date, it's simply a UNIX timestamp. Now let's add in a Drupal API function to format the date and then we can leverage any custom Date Formats created in the Drupal UI at /admin/config/regional/date-time/formats. Of course we want to add this to our preprocess function keeping in mind that we add any logic to template.php and not to our node template. Searching through the API, there is a function called format_date. I can add that on to our code from above.
Note the two new additions, 'format_date' which is the api function and then the custom time format 'mdy'. 'mdy' is not to be confused with a raw PHP time format here, it's actually the name of the custom time format I created in the Drupal UI (which in the end does use PHP time formats). Our preprocess function now looks like this:
Render the Formatted Variable
The node variable to render the date stays the same:
With our newly formatted date using a Drupal API function, it will now print out as:
Voila, a nicely formatted date of the time the image was uploaded converted from UNIX time to a PHP date format all with a simple preprocess function. As you can see the possibilities are endless here. Some other API functions I had fun experimenting with were 'image_style_url' where you can render the URL to a specific image style and 'format_size' which converts a UNIX file size to an actual MB / KB size similar to what the 'format_date' API function does.