You are here

How to Code a Custom Drupal Field Formatter for an Existing Field

paulbooker's picture
Submitted by paulbooker on Mon, 01/20/2014 - 15:42
/**
 * Implements hook_field_formatter_info().
 */
function mymodule_field_formatter_info() {
  return array(
    'mymodule_screenshot' => array(
      'label' => t('Preview image'),
      'field types' => array('link_field'),
      'settings' => array(
        'mymodule_screenshot_size' => 'small',
        'mymodule_screenshot_cache' => 1),
    ),
    'mymodule_screenshot_linked' => array(
      'label' => t('Preview image, as link'),
      'field types' => array('link_field'),
      'settings' => array(
        'mymodule_screenshot_size' => 'small',
        'mymodule_screenshot_cache' => 1),
    ),
  );
}
/**
 * Implements hook_field_formatter_view().
 */
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $lang_code, $items, $display) {
  $element = array();
  $theme_function = $display['type'];
  $settings = $display['settings'];
  $size = $settings['mymodule_screenshot_size'];
  $cache = $settings['mymodule_screenshot_cache'];

  foreach ($items as $delta => $item) {
    $element[$delta] = array(
      '#markup' => theme($theme_function, array('element' => $item, 'size' => $size, 'cache' => $cache)),
    );
  }
  return $element;
}
/**
 * Theme function for mymodule screenshot
 */
function theme_mymodule_screenshot($vars) {
  $url = $vars['element']['url'];
  $size = $vars['size'];
  $cache = $vars['cache'];

  $screenshot = _mymodule_request($url, $size, $cache);

  if ($screenshot) {
    $theme_mymodule = '';
  }
  else {
    $theme_mymodule = '

No Image

'; } return $theme_mymodule; } /** * Theme function for mymodule screenshot linked */ function theme_mymodule_screenshot_linked($vars) { $url = $vars['element']['url']; $size = $vars['size']; $cache = $vars['cache']; $screenshot = _mymodule_request($url, $size, $cache); if ($screenshot) { $theme_mymodule = ''; } else { $theme_mymodule = '

No Image

'; } return $theme_mymodule; }