datetimehideseconds.module in DateTime hide Seconds 8
File
datetimehideseconds.module
View source
<?php
use Drupal\datetime\Plugin\Field\FieldWidget\DateTimeWidgetBase;
function datetimehideseconds_element_info_alter(array &$types) {
$types['datetime']['#process'][] = 'datetimehideseconds_process_element';
}
function datetimehideseconds_process_element($element) {
if (!empty($element['#datetimehideseconds']['hide'])) {
$element['time']['#attributes']['title'] = t('Enter a valid time - e.g. @format', [
'@format' => (new \DateTime())
->format('h:i'),
]);
if ($element['#date_time_element'] !== 'none') {
$element['#date_time_format'] = 'H:i';
}
if (!empty($element['time']['#value'])) {
$parts = explode(':', $element['time']['#value']);
$parts = array_splice($parts, 0, 2);
$element['time']['#value'] = implode(':', $parts);
}
$element['time']['#attributes']['step'] = 60;
}
return $element;
}
function datetimehideseconds_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
$widget = $context['widget'];
if ($widget
->getThirdPartySetting('datetimehideseconds', 'hide')) {
$element['value']['#datetimehideseconds']['hide'] = TRUE;
if (isset($element['end_value'])) {
$element['end_value']['#datetimehideseconds']['hide'] = TRUE;
}
}
}
function datetimehideseconds_field_widget_third_party_settings_form(\Drupal\Core\Field\WidgetInterface $widget, \Drupal\Core\Field\FieldDefinitionInterface $field_definition, $form_mode, $form, \Drupal\Core\Form\FormStateInterface $form_state) {
$element = [];
if ($widget instanceof DateTimeWidgetBase) {
$element['hide'] = [
'#type' => 'checkbox',
'#title' => t('Hide seconds'),
'#description' => t('This will have no effect if there is no time widget.'),
'#default_value' => $widget
->getThirdPartySetting('datetimehideseconds', 'hide'),
];
}
return $element;
}
function datetimehideseconds_field_widget_settings_summary_alter(&$summary, $context) {
$widget = $context['widget'];
if ($widget instanceof DateTimeWidgetBase) {
if ($widget
->getThirdPartySetting('datetimehideseconds', 'hide')) {
$summary[] = t('Hide seconds.');
}
else {
$summary[] = t('Do not hide seconds.');
}
}
}