Skip directly to content

Drupal 7 Custom Field Formatter

rteijeiro's picture
on Fri, 11/16/2012 - 21:38

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 ;)

 

Comments

anon's picture

rteijeiro's picture

Yes it's a great module.

Thank you for sharing ;)

oskar calvo's picture

Hello Ruben the post it's great but I think that should be used a "tpl" file with this view format, this is the good "drupal way" for theming fields.

 

Oskar

rteijeiro's picture

Hi Oskar.

Thank you for your comment. In future posts I will write about tpls and theming in Drupal ;)

Post new comment