2

I have a field of type X, and it's output is not quite the way I want to it to be. I would like it to look like Y instead. How can I do that?

2

I usually solve this type of problem by implementing a custom field formatter, which is what controls how a field is rendered.

Below is sample code to implement a basic single delta field formatter. It is used on normal "text" fields, and will simple output todays date, with a single setting for in what format to output the date.

Since this particular example does not actually use the field data, it's important to know that you need the field to have some value, or Drupal will ignore it.

// Declare a new field formatter.
function hook_field_formatter_info() {
  return array(
    'custom_current_date' => array(
      'label' => t('Current date'),
      'field types' => array('text'),
      'settings' => array('date_configuration' => 'm'),
    ),
  );
}

// Form API callback for the formatters settings form
function hook_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

  $element = array(
    'date_configuration' => array(
      '#type' => 'textfield',
      '#title' => t('Date configuration'),
      '#default_value' => $settings['date_configuration']
    ),
  );

  return $element;
}

// Output a message showing what the current field settings are.
function hook_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

  return 'Date config is ' . $settings['date_configuration'];
}

// Actual field output goes under the #markup key. Add a loop instead of the
// leading 0 to support multi-value fields.
function hook_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $settings = $display['settings'];

  return array(0 => array('#markup' => date($settings['date_configuration'])));
}

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.