Drupal how to add another formatter to a cck field using hook_field_formatter_info

Posted by: 
Dominique De Cooman

How to add another formatter to a cck field? A cck formatter is basically a theming function where the value of field is ran through. Formatters are available at "admin/content/node-type/[your node type]/display" in the cck interface.

The previous screenshot shows your build modes of a node blog. Here you can change which formatter is used for which build mode. For example you might run the image through a different formatter in the full node than in the teaser. This screenshot is without the display suite. If possible you should use the display suite. It will make your theming life easier. You'll be able to define custom build modes too. Then it looks like this.

To add another formatter to the node displays you implement of hook theme. In our example we want to use a formatter for our title. The formatter will use the h3 tag to render our title.

<?php

/**
 * Implementation of hook_theme().
 */
function your_module_theme() {
  
$theme_functions = array();

  
// Formatter theming functions.
  
$formatters = array(
    
'your_module_title_h3',
  );

  foreach (
$formatters as $formatter) {
    
$theme_functions[$formatter] = array(
      
'arguments' => array('field' => NULL),
    );
  }
 
  return 
$theme_functions;
}

?>

Then you define your theme function

<?php

function theme_your_module_title_h3($field) {

  return 
'<h3>'.$field['object']->title.'</h3>';

}

?>

And in the final step you expose this formatter to cck using the hook_field_formatter_info()

<?php

/**
 * Implementation of hook_field_formatter_info(),.
 */
function your_module_field_formatter_info() {
    return array(
    
'your_module_title_h3' => array(
      
'label' => t('Renders text tru a h3 tag'),
      
'field types' => array('text'),
      
'multiple values' => CONTENT_HANDLE_MODULE,
    ),
  );
}

?>

Finally when you dont want to do all this in code (which you probably should because it is easier to control) there is a handy module called custom formatters

Add new comment

Who are you?


By knowing who you are you will be directed to a page where we have displayed all our drupal services relevant to your professional identity.