Skip to content

Instantly share code, notes, and snippets.

@pepeloper
Last active March 27, 2017 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pepeloper/a8dff09863fe4d2ab166cb7f53dfa641 to your computer and use it in GitHub Desktop.
Save pepeloper/a8dff09863fe4d2ab166cb7f53dfa641 to your computer and use it in GitHub Desktop.
Custom field formatter settings

Drupal Snippet

This snippet is a follow up from this one: Crear formato personalizado para un campo de tipo fecha

In order to implement a settings form to our custom field formatter we only need to use the 'settings' parameter in the field formatter declaration (in hook_field_formatter_info()) and a few hooks.

Through the hook_field_formatter_settings_summary() we can implement a summary showing the configuration used.

hook_field_formatter_settings_summary

With the hook_field_formatter_settings_form() we can implement the settings form itself. Then finally we only need to use the configuration on our hook_field_formatter_view() through the $display array like this:

$display['settings']['date_format'];

Code

  <?php 

  /**
   * Implements hook_field_formatter_info().
   */
  function custom_module_field_formatter_info() {
    return array(
      'custom_date_format' => array(
        'label' => t('Custom date format'),
        'field types' => array('date', 'datestamp', 'datetime'),
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
        'settings' => array(
          'date_format' => 'd M',
        ),
      ),
    );
  }

  /**
   * Implements hook_field_formatter_settings_summary().
   */
  function custom_module_field_formatter_settings_summary($field, $instance, $view_mode) {
    $display = $instance['display'][$view_mode];
    $settings = $instance['display'][$view_mode]['settings'];

    if ($display['type'] == 'custom_date_format') {
      $output = t('Date render format: @format', array('@format' => $settings['date_format']));
    }

    return (isset($output)) ? $output : '';
  }

  /**
   * Implements hook_field_formatter_settings_form().
   */
  function custom_module_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
    $display = $instance['display'][$view_mode];
    $settings = $display['settings'];

    if ($display['type'] == 'custom_date_format') {
      $element['date_format'] = array(
        '#type' => 'textfield',
        '#title' => t('Example date format'),
        '#default_value' => 'd M',
      );
    }

    return $element;
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment