I'm working on a way to alter the way a date field, field_node_date, is formatted when rendered.
Currently, on the content type I'm working on, the Long format is being used (e.g. Monday 18 January 2016 - 22:55) and "Both Start and End dates" are displayed by default (on Display settings for any view mode this node is using). As a result, in the node's template,
<?php print render($content['field_node_date']); ?>
is rendering the field as expected.
I've added a new checkbox field to the content type. When users check that checkbox, I only want the date part of the field to be rendered, ie without the time, e.g.
"Monday 18 January 2016"
instead of
"Monday 18 January 2016 - 16:55"
when only a start date is entered, the same for a date range, e.g.
"Monday 18 January 2016 to Tuesday 19 January 2016"
instead of
"Monday 18 January 2016 - 16:54 to Tuesday 19 January 2016 - 19:44"
I tried overriding the theme registry to provide my custom theme callbacks for a single date and a date range:
function mymodule_theme_registry_alter(&$theme_registry) {
if (isset($theme_registry['date_display_range'])) {
$theme_registry['date_display_range']['function'] = 'custom_range_date_display_format';
}
if (isset($theme_registry['date_display_single'])) {
$theme_registry['date_display_single']['function'] = 'custom_single_date_display_format';
}
}
and then copying over date's theme_date_display_range() and theme_date_display_single() functions from date.theme and alter them to return the dates without the time. But there's no way to hook into each separate node withing the scope of this functions and see if the "don't show the time" field is checked so the returned date format would always be the same, either with the time or not, for all my nodes.
Another solution would be to go straight into the node's template and replace
<?php print render($content['field_node_date']); ?>
with something like
<?php print format_date(strtotime($date_field_value) ,'custom','whatever format I need for each node'); ?>
and create the same HTML structure for a single date or a range of dates. But that doesn't cover other view modes and it's not very clean.
I also tried to find the node hooks that would allow me to alter the date but I now see that no matter what format is selected, the date item always holds the date field's value as it's saved on the database and then only the markup changes. Programmatically altering the markup of the field would probably not be a preferred solution as any change of the format on the UI under display settings (e.g. from long to short etc) would be ignored.
I'd also like to avoid adding a new date format / type to my db
A good solution that would allow me to hook into my nodes, check if that checkbox is checked and then enforce my preferred custom date format every time the node is rendered would be ideal.
I'd appreciate any suggestions, thanks.