[Drupal] How to create a field formatter programmatically in Drupal sites

| | 3 min read

In Drupal, if you have a content type and you want to change the output of any field to something else you can use field formatter with field API. This enables a display settings for any fields in a content type and where you can manage the output as you wish. This article shares how to create a field formatter for your Drupal content types. There are some contributed modules for custom field formatters. But if you really want to create or learn about creating a field formatter programmatically, just go through this article

Here I am going to show you with an example module.

Create your module with "MODULE_NAME.info" and "MODULE_NAME.module". Inside MODULE_NAME.module you can begin to create a field formatter.

Main hooks used in this example are:

  • hook_field_formatter_info
  • hook_field_formatter_settings_summary
  • hook_field_formatter_settings_form
  • hook_field_formatter_view

Now we can start with hook_field_formatter_info

In this hook with the help of machine name you are actually giving Drupal information that there is a new formatter and this formatter will get displayed in the formatter list inside your content type's display settings page.

function MODULE_NAME_field_formatter_info() {
  return array(
    'MODULE_NAME' => array(
      'label' => t('Colorized text '),
      'field types' => array('text'),
      'settings'  => array(
        'color' => 'red',
      )
    ), 
  ); 
}

In this example I am using 'text' as a field type. So that whenever I add a text field, I can set the formatter for same field.

Now go to admin › structure › content type › manage fields. Just create a field with text as field type. Now go to manage display settings.

By default there will be three formatters for text field. I think they are default plain, text and trimmed. Here if you created the above hook you can see the new formatter with the name you are given.

Next we need to create form where we can change the settings for your custom field formatter.

Create a hook called MODULE_NAME_field_formatter_settings_summary

Here you can specify the summary of you formatter in "manage display". Once you implement this hook there will be a gear icon next to summary where we can change the formatter settings.

function MODULE_NAME_field_formatter_settings_summary($field, $instance, $view_mode) {  
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $summary = t('Colorize the text to @color', array(
    '@color'     => $settings['color'],
  ));
  return $summary;   
}

Next you need to create a form for your formatter. For this you can implement MODULE_NAME_field_formatter_settings_form

Here you are creating a form which will display when someone click on the gear icon. In this example I'm going to show how to change color of a text when someone select the color that I specify in field formatter settings.

For this I am going to create a form where you can select a particular color from a drop down menu.

function MODULE_NAME_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $element = array();
  $element['color'] = array(
    '#type'           => 'select',
    '#title'          => t('Color'),
    '#description'    => t('Select in what color you want to see the text'),
    '#default_value'  => $settings['color'],
    '#options'        => array(
      'red'  => 'Red',
      'green' => 'Green',
      'gray' => 'Gray',
      'pink' => 'Pink',
    ),
  );
  

Now you are done with all settings for formatter. But the important part is that you need to display an HTML output in the content page of same content type. For this, you need to create another hook called hook_field_formatter_view

function MODULE_NAME_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $settings = $display['settings'];
  $color = $settings['color'];
  foreach ($items as $key => $item) {
    $text_value = $item['safe_value']; // Getting the actual value
    $new_color = _get_color($color);
    if (isset($new_color)){
      $replaced = _replace_string($text_value, $new_color);
    }
    $replaced = _replace_string($text_value, $color);
    if (isset($text_value)) {
      $element[0]['#markup'] = $replaced;
    }
  }
  return $element;
}

Here I am going to write two custom functions to select a number from a paragraph.


function _replace_string($text_value, $color) {
  preg_match_all('!\d+!', $text_value, $matches);
  foreach ($matches as $values) {  
    foreach ($values as $val) {
      $styles[] = '<font color="' . "$color" . '">' . $val. '</font>';  
    }  
  }
    $newphrase = str_replace($values, $styles, $text_value);
  return $newphrase; 
}

You can select any color by adding more cases in the following code.


function _get_color($color) {
  switch ($color) {
    case 'cool':
      return '#FF8EFF';
    break;
    default:
      return '#000000';
  }
}

So you are done with field formatter. Enable the module and start changing the color according to your wish. I hope this was helpful. Thank you :)