Drupal - How do I write an additional field formatter for an existing field
Personally I'd say a formatter is the better solution.
There are only two hooks you need to implement:
hook_field_formatter_info()
hook_field_formatter_view()
For example:
function MYMODULE_field_formatter_info() {
return array(
'my_formatter' => array(
'label' => t('My formatter'),
// The important bit...
'field types' => array('field_type'),
),
);
}
function MYMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
$settings = $display['settings'];
$element = array();
if ($display['type'] == 'my_formatter') {
foreach ($items as $delta => $item) {
$element[$delta] = array('#markup' => $item['value']);
}
}
return $element;
}
For a more in-depth look, download the Examples module and look at field_example - there's plenty of code and documentation there to get you on your way.
you can develop a custom module or use "Custom formatters" module.
In the first case you have to write a module which implements some Drupal 7 hooks: hook_field_formatter_info()
, hook_field_formatter_view()
and hook_theme()
. hook_field_formatter_info()
Is used to declare the formatter type. This function returns an array with the formatter description. The key will be the formatter name and it will have an array with the label and the field types. After you have to implement hook_field_formatter_view()
and hook_theme()
in order to define the template. You can find more details about the Field Formatter API in the docs.
In the second case you can use Custom Formatters module which allows to create custom display formatters for every field. With this module you can create the formatter using custom PHP code or HTML code with tokens.
I suggest the second way because is very easy to use and to configure.