Drupal 7 Custom Field Formatter
If you want a custom field formatter for an existing drupal field you only need a few lines of code to make it done.
The hook we are going to use are: hook_field_formatter_info and hook_field_formatter_view
In hook_field_formatter_info we will declare the new formatters for the existing field. For example these are four new formatter for the link field:
/**
* Implements hook_field_formatter_info().
*/
function easythumb_field_formatter_info() {
return array(
'easythumb_small' => array(
'label' => t('Small screenshot'),
'field types' => array('link_field'),
),
'easythumb_medium' => array(
'label' => t('Medium screenshot'),
'field types' => array('link_field'),
),
'easythumb_medium2' => array(
'label' => t('Medium 2 screenshot'),
'field types' => array('link_field'),
),
'easythumb_large' => array(
'label' => t('Large screenshot'),
'field types' => array('link_field'),
),
);
}
And here you can see the custom formatters in action:
The following step is tell drupal what to do with the new formatters when the field is shown. Here we will need the hook_field_formatter_view as the following example:
/**
* Implements hook_field_formatter_view().
*/
function easythumb_field_formatter_view($entity_type, $entity, $field, $instance, $lang_code, $items, $display) {
$elements = array();
foreach ($items as $delta => $item) {
$elements[$delta] = array(
'#markup' => theme('easythumb_field_formatter_' . $display['type'], array('element' => $item)),
);
}
return $elements;
}
Whe can know what formatter was selected with the $display['type'] value so we can theme the field with our custom theme function. The full code of the examples is located in this drupal sandbox.
Hope it wil be useful for future projects ;)