1

I have a field that I created using hook_field_extra_fields, and I want it to have a cogwheel like in the image below, so that I can customize it. Right now the only format setting for the field is "Visible". Any ideas on how to enable the formatter settings for that field?

Note that I am also using display suite.

enter image description here

1 Answer 1

1

You can use hook_field_formatter_settings_form to add formatting of the field as shown in example below:

function example_field_formatter_info() {
  $info = array();
  $info['default_formatter'] = array(
    'label' => t('Show as link'),
    'field types' => array('example_field_type'),
     'settings' => array('target' => '_blank'), // <--- THIS
  );
  return $info;
}

function example_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $element = array(); 
  if ($display['type'] == 'default_formatter') {
    $element['target'] = array(
      '#type' => 'select',
      '#title' => t('HREF target'),
      '#options' => array('_blank' => 'New window', '_self' => 'Same window'),
      '#default_value' => $settings['target'],
      '#description' => t('Control where the link opens (i.e. set the TARGET attribute of the A element).'),
    );
  }
  return $element;
}

function example_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $settings = $display['settings']; // Key needs to be defined in info array (who knew?)
  $element = array();
  if ($display['type'] == 'default_formatter') {
    $target = $settings['target'];
    foreach ($items as $delta => $item) {
      $element[$delta]['#markup'] = "<a href=\"{$item['href']}\" target=\"{$target}\">{$item['label']}</div>";
    }
  }
  return $element;
}

Update #1:

/**
 * Implements hook_field_formatter_settings_summary().
 */
function example_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $summary = t('Show as link'); // we use t() for translation and placeholders to guard against attacks
  return $summary;
}
3
  • To show cogwheel, you need to implement hook_field_formatter_settings_summary() as shown in Update #1 Mar 10, 2015 at 9:09
  • hook_field_formatter_settings_summary() doesn't seem to be called. I should call it like this: MY_MODULE_field_formatter_settings_summary(), right?
    – Marian
    Mar 10, 2015 at 14:30
  • correct, you need to replace hook word by your module name. Mar 10, 2015 at 17:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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