How To Create a Custom Format for a Date Field

05/22/2017
Crear formato personalizado para un campo de tipo fecha

In this post, you will learn how to create a custom date format for Drupal 7.

A field format is a functionality or a feature which allows to configure the display of a field for a presentation mode (default, summary, etc.). When some fields are provided to add to the content types from the Drupal core or from a contributed module, these ones usually display some generic presentation formats that although they are the most used, they do not always fit the display that we need for our projects.

As an example, we will use a date field provided by the Date module which it is in the Basic Page content. As we can observe in the following image, in the configuration of the presentation for the content type for the default presentation mode, the Date field offers three possible display formats (which are configurable) plus one format to be hidden. The first one would show the date and time, the second one shows the time passed from that date up to the present time and the third one would show the date in a plan text.

None of these formats works for us because we want a presentation format that only shows the day and month and also show these values in two separate <span> tags, because this is required by the front-end area to fit the project design.

Well, to create our personalized custom format, the following steps are as follows:

Step 1: In the module file of the custom module where we would like to add the functionality, we will add the following code. It consists of a part of the hook_field_formatter_info and the hook_field_formatter_view that are used to register the new format that, in our case, it would apply to the field types date, datestamp and datetime. On the other hand, the hook_theme is defined to register the function of theme and such a function renders the content as we would like to present. It is in this function where the format logic is implemented.


/**
 * 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,
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function custom_module_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $elements = array();
  foreach ($items as $delta => $item) {
    $element = array(
      'element' => $item,
      'field' => $instance,
      'display' => $display
    );
    $elements[$delta] = array(
      '#theme' => 'custom_module_formatter_' . $display['type'],
      '#element' => $element,
      '#field' => $field,
    );
  }

  return $elements;
}

/**
 * Implements hook_theme().
 */
function custom_module_theme() {
  $themes = array(
    'custom_module_formatter_custom_date_format' => array(
      'variables' => array(
        'element' => NULL,
        'field' => NULL,
      ),
    ),
  );
  return $themes;
}

/**
 * Implements theme function
 */
function theme_custom_module_formatter_custom_date_format($vars) {
  $element = $vars['element'];
  $field = $vars['field'];

  // Configure custom date
  $format_date = 'd M';
  $timezone_bd = date_get_timezone_db($field['settings']['tz_handling']);
  $publish_date = DateTime::createFromFormat('Y-m-d H:i:s', $element['element']['value'], new DateTimeZone($timezone_bd));
  $date = format_date($publish_date->getTimestamp(), 'custom', $format_date);
  $date = explode(' ', $date);

  // Declare array for render content with custom format and tags
  $render_array = array(
    'date' => array(
      'date-day' => array(
        '#prefix' =>'<span class="date-day">',
        '#markup' => $date[0],
        '#suffix' => '</span>'
      ),
      'date-month' => array(
        '#prefix' =>'<span class="date-month">',
        '#markup' => $date[1],
        '#suffix' => '</span>'
      ),
    ),
    '#theme_wrapper' => array('container'),
  );

  return render($render_array['date']);
}

Step 2: To remove the Drupal cache.
Step 3: Once added the code and removed this cache, we will have available a new date format in the configuration of the presentation for our content type for the Date field, which will call Custom date format.


 

Step 4: Once selected this format and saved the content type presentation settings, if you create a basic page content, we can observe that the date appears in our new format and in two separate <span> tags.


Note: There are two hooks (hook_field_formatter_settings_form and hook_field_formatter_settings_summary) which are used to add a configuration section from the format that we will see shortly in a new entry.

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.