Custom field formatter settings

27/03/2017
Custom field formatter settings

This snippet for Drupal 7 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 by La Drupalera

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;
  }

 

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.