10

I would like to write a new field formatter for an existing field type. I don't want to replace any existing formatters but offer a new option.

Or am I better off using a theme_preprocess_field() to do minor alterations? But this seems to be harder to maintain and I'd like to keep my content editors options open (and in the GUI).

Can someone point me to an example of the proper way to do this?

13

Personally I'd say a formatter is the better solution.

There are only two hooks you need to implement:

For example:

function MYMODULE_field_formatter_info() {
  return array(
    'my_formatter' => array(
      'label' => t('My formatter'),
      // The important bit...
      'field types' => array('field_type'),
    ),
  );
}

function MYMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $settings = $display['settings'];
  $element = array();

  if ($display['type'] == 'my_formatter') {
    foreach ($items as $delta => $item) {
      $element[$delta] = array('#markup' => $item['value']);
    }
  }

  return $element;
}

For a more in-depth look, download the Examples module and look at field_example - there's plenty of code and documentation there to get you on your way.

  • You may also be interested in implementing hook_field_formatter_settings_form and hook_field_formatter_settings_summary so that you can give your user some options to change how the field is presented. – ndvo Feb 20 '18 at 14:51
2

you can develop a custom module or use "Custom formatters" module.

In the first case you have to write a module which implements some Drupal 7 hooks: hook_field_formatter_info(), hook_field_formatter_view() and hook_theme(). hook_field_formatter_info() Is used to declare the formatter type. This function returns an array with the formatter description. The key will be the formatter name and it will have an array with the label and the field types. After you have to implement hook_field_formatter_view() and hook_theme() in order to define the template. You can find more details about the Field Formatter API in the docs.

In the second case you can use Custom Formatters module which allows to create custom display formatters for every field. With this module you can create the formatter using custom PHP code or HTML code with tokens.

I suggest the second way because is very easy to use and to configure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.