ReferralField - Part Three - Formatters and Presenting Output

In Part three of our CCK field widget tutorial, we will finish our skeleton module and create our default formatter. Implementing a Formatter requires implementing hook_field_formatter_info(), hook_field_formatter, and usually a theme callback, so theme developers can override the HTML output of the formatter if necessary.

hook_field_formatter_info
Like our previous info hooks, this hook returns a simple array, keyed on the machine readable name of the formatter and has an internal array of the fields the formatter can be applied to.

<?php
/**
 * Implementation of hook_field_formatter_info().
 */
function referralfield_field_formatter_info() {
 
$formatters = array(
   
'default' => array(
     
'label' => 'Default',
     
'field types' => array('referralfield'),
    ),
  );
  return 
$formatters;
}
?>

Feels familiar after hook widget doesn't it.

hook_field_formatter
This is the work horse of the Formatter API. It recieves the field definition, a single item, and the name of the end user selected formatter. It is expected to return html for output. My recommended practice here is to delegate the actual rendering to a theme callback so theme developers can override the output based on their theme's needs.

<?php
/**
 * Implementation of hook_field_formatter().
 */
function referralfield_field_formatter($field$item$formatter) {
 
// switch formatter in case we implement multiple formatters.
 
switch ($formatter) {
    case 
'default':  return theme('referralfield_formatter_default'$item);
  }
}

/**
 * callback function for the theme
 */
function theme_referralfield_formatter_default($item) {
 
$output '';
  if (isset(
$item['imageurl'])) {
   
$output .= l('<img src="'check_plain($item['imageurl']) .'" />'$item['target_url'], array(), 
                       
NULLNULLFALSETRUE);
  } else {
   
$output .= check_markup($item['description'], $item['description_format']);
  }
 
$output .= l(t('Link'), $item['target_url']);
  return 
$output;
}
?>

Woot. We should have a basic CCK field now. So sum up what we've covered to this juncture. CCK fields consist of three components Fields, Widgets, and Formatters. Fields provide the Data Layer and Data Layer validation. Widgets are responsible for collecting user input and preparing it to be handed over to the data layer. Formatters are responsible for presenting the field data to the end user.

So far, we've made a manual input widget and a simple link formatter for output. In the continuation of this series we will build an Amazon ASIN widget for listing amazon items on your site, Create a click thru tracking formatter.