Create a custom field formatter in Drupal 7

Field formatters are used to render CCK fields in node views. Drupal provides default formatters. To customize the output of a field and have it apply it to multiple fields of the same type, a custom formatter needs to be created. 

The following tutorial is an example of how to add a formatter to the field of type link. To start look at the default formatters available for the link field in a Content Type. In Drupal 7 the available formatters for a field are found by going to Structure > Content types > The content type > Manage display. 

The image above shows 7 different formatters that are 7 different ways to display the link field. This example shows how to add a formatter to this field which will display the Title as the link and the URL as plain text, called "Title as link, URL as plain text". To access the link field type it is necessary to have the link module installed.

Step one to creating a formatter is declaring it using Drupal hooks and the second step is changing the display of the field using the theme hook and loading a template file.

1. Declaring the formatter

To declare a formatter in Drupal 7, two hooks need to be called: hook_field_formatter_info() and hook_field_formatter_view()

<?php
/**
* Implements hook_field_formatter_info().
*/
function mymodule_field_formatter_info() {
 
$info = array(
   
'website' => array(
     
'label' => t('Title as link, URL as plain text'),
     
'field types' => array('link_field'),
     
'description' => t('Displays Title as a link and URL as plain text.'),
    ),
  );
  return
$info;
}
?>

For any other field types other than link field you will have to change the field 'field types' to the corresponding field type.

<?php
/**
* Implements hook_field_formatter_view().
*/
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
 
$element = array();
  switch (
$display['type']) {
    case
'website':
      foreach (
$items as $delta => $item) {
       
$element[$delta] = array(
         
'#theme' => 'mymodule_website',
         
'#title' => $entity->field_website['und'][0]['title'],
         
'#url' => $entity->field_website['und'][0]['url'],
        );
     }
      break;
  }
  return
$element;
}
?>

The #title and #url are variables which will be accessible in the template file.

2. Theming the formatter

To theme the formatter, the theme hook needs to be implemented. This is where the template file is called.

<?php
/**
* Implements hook_theme().
*/
function mymodule_theme() {
  return array(
   
'mymodule_website' => array(
     
'template' => 'mymodule_website',
     
'variables' => array(
       
'title' => NULL,
       
'url' => NULL,
      ),
    ),
  );
}
?>

The name of the template file is  mymodule_website.tpl.php which should be created in the directory of the custom module. Below is an example of what it could look like.


<a href="<?php print $url; ?>"><?php print $title; ?></a>
<div class="website-title"><?php print $url; ?></div>

The image below shows the new formatter in the dropdown:

The formatter can now be used for any link field type. It will also be applied when using views.

Another hook, which is worth taking a look at: hook_field_formatter_prepare_view, it can be used to do any modifications before rendering the field.

Comments

6

It's also worth checking out the Custom Formatters module, which allows field formatters to be created via the Drupal frontend and exported to either Features or as the Drupal API functions.

Hi. I would like to render this field programmatically, but can't have effects. How should I do it? I'm trying this: print drupal_render(field_view_field('node', $node, 'my_custom_field', array('type' => 'my_custom_format'))); but I recive empty array.

Thanks for the excellent post.

Great tutorial! Thanks a lot. I tried your code but I get an error: Notice: Undefined property: stdClass::$field_website in mymodule_field_formatter_field_formatter_view() I might have to change: 'website' => array to something else. Could you please give me some feedback. Thanks a lot. Chris
Daniel's picture

Could you post your code? it'll be easier to debug, cheers.

Really Nice tutorial.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>