Automated field formatter settings summaries in Drupal

Posted By Brad Czerniak on Thursday, October 23, 2014 - 15:30

Drupal developers [hopefully] find themselves writing "field formatters" fairly often. These pieces of code add ways to display the data stored in fields, so having an arsenal of formatters can come in handy.

Making formatters is often straightforward, but some of the work gets repetitive and tedious. The snippet below should allow you to at least get up to speed more quickly, if not make the "settings summary" a worry of the past.

The snippet

  1. /**
  2.  * Implements hook_field_formatter_settings_summary().
  3.  */
  4. function MYMODULE_field_formatter_settings_summary($field, $instance, $view_mode) {
  5.   $display = $instance['display'][$view_mode];
  6.   $settings = $display['settings'];
  8.   $module_name = basename(__FILE__, '.module');
  9.   $form = call_user_func_array($module_name . '_field_formatter_settings_form', array(
  10.     $field,
  11.     $instance,
  12.     $view_mode,
  13.     array(),
  14.     array(),
  15.   ));
  17.   $summary = array();
  18.   switch ($display['type']) {
  19.     case 'NAME_OF_YOUR_FORMATTER':
  20.       foreach ($settings as $key => $setting) {
  21.         if (is_numeric($setting)) {
  22.           $setting = ($setting) ? 'Yes' : 'No';
  23.         }
  24.         $summary[] = t('@key: @setting', array(
  25.           '@key' => $form[$key]['#title'],
  26.           '@setting' => $setting,
  27.         ));
  28.       }
  30.       break;
  31.   }
  33.   return implode('<br />', $summary);
  34. }

What the heck it does

This hook lets you set the display of a summary of the settings on the "manage display" screen for a particular entity view mode. This snippet largely automates away the need to write anything for the hook.

The function calls the settings form (in a clever way) to get the keys associated with the setting values. So, as long as the form keys make sense as the summary keys, this summary function will drop in and display a listing of the settings.

The little is_numeric conditional turns any boolean settings to 'Yes' or 'No'. If you have actual numeric settings, you may need to tweak this to display the number instead. If you have a mix, this will not be a drop-in solution per se. I think this can be tweaked (using the settings $form array) to handle those circumstances automatically, but I ran out of time for that and didn't have the use case at the time. Stay tuned, as I will update this helper as I (and hopefully others) use it and improve upon it.

Hope you like it

It's not a big or glamorous piece of code. This is just something that came to mind that I thought could be a bit of a time-saver for other developers.