Skip to content

Instantly share code, notes, and snippets.

@kalabro
Last active December 10, 2015 01:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kalabro/4359431 to your computer and use it in GitHub Desktop.
Save kalabro/4359431 to your computer and use it in GitHub Desktop.
Drupal 7: Define Age formatter for date fields.
<?php
/**
* Define Age formatter for date fields.
*/
/**
* Implements hook_field_formatter_info().
*/
function kalabro_field_formatter_info() {
$formatters = array(
'date_age' => array(
'label' => t('Age'),
'field types' => array('date', 'datestamp', 'datetime'),
'settings' => array(
'show_raw_date' => 0,
'raw_date_format' => 'short',
),
),
);
return $formatters;
}
/**
* Implements hook_field_formatter_settings_form().
*/
function kalabro_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
$display = $instance['display'][$view_mode];
$settings = $display['settings'];
$id = drupal_html_id('show_raw_date');
$element['show_raw_date'] = array(
'#type' => 'checkbox',
'#title' => t('Show full date after age'),
'#default_value' => $settings['show_raw_date'],
'#attributes' => array('id' => $id),
);
$element['raw_date_format'] = array(
'#type' => 'select',
'#title' => t('Date format'),
'#default_value' => $settings['raw_date_format'],
'#options' => date_format_type_options(),
'#states' => array(
'visible' => array(
'#' . $id => array('checked' => TRUE),
),
),
);
return $element;
}
/**
* Implements hook_field_formatter_settings_summary().
*/
function kalabro_field_formatter_settings_summary($field, $instance, $view_mode) {
$display = $instance['display'][$view_mode];
$settings = $display['settings'];
$value = $settings['show_raw_date'] ? t('yes') : t('no');
$summary = t('Show full date after age') . ': <em>' . $value . '</em>';
return $summary;
}
/**
* Implements hook_field_formatter_view().
*/
function kalabro_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
$element = array();
$settings = $display['settings'];
if ($display['type'] == 'date_age') {
foreach ($items as $delta => $item) {
if (!empty($item['value'])) {
$age = _ij_main_count_age($item['value']);
$element[$delta] = array('#markup' => $age);
if ($settings['show_raw_date']) {
$element[$delta]['#suffix'] = ' (' . format_date(strtotime($item['value']), $settings['raw_date_format']) . ')';
}
}
}
}
return $element;
}
/**
* Helper for age count.
*/
function _kalabro_count_age($date_str) {
$diff = date_diff(new DateTime($date_str), new DateTime());
return $diff->y;
}
@alex-bukach
Copy link

What is _ij_main_count_age()? Should it be _kalabro_count_age() instead?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment