You are here

datetimehideseconds.module in DateTime hide Seconds 8

File

datetimehideseconds.module
View source
<?php

use Drupal\datetime\Plugin\Field\FieldWidget\DateTimeWidgetBase;

/**
 * Implements hook_element_info_alter().
 */
function datetimehideseconds_element_info_alter(array &$types) {
  $types['datetime']['#process'][] = 'datetimehideseconds_process_element';
}

/**
 * Element process callback for datetime fields.
 */
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);
    }

    // Remove seconds in browsers that support HTML5 type=date.
    $element['time']['#attributes']['step'] = 60;
  }
  return $element;
}

/**
 * Implements hook_field_widget_form_alter().
 */
function datetimehideseconds_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {

  /** @var \Drupal\Core\Field\WidgetInterface $widget */
  $widget = $context['widget'];
  if ($widget
    ->getThirdPartySetting('datetimehideseconds', 'hide')) {
    $element['value']['#datetimehideseconds']['hide'] = TRUE;
    if (isset($element['end_value'])) {
      $element['end_value']['#datetimehideseconds']['hide'] = TRUE;
    }
  }
}

/**
 * Implements hook_field_widget_third_party_settings_form().
 */
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;
}

/**
 * Implements hook_field_widget_settings_summary_alter().
 */
function datetimehideseconds_field_widget_settings_summary_alter(&$summary, $context) {

  /** @var \Drupal\Core\Field\WidgetInterface $widget */
  $widget = $context['widget'];
  if ($widget instanceof DateTimeWidgetBase) {
    if ($widget
      ->getThirdPartySetting('datetimehideseconds', 'hide')) {
      $summary[] = t('Hide seconds.');
    }
    else {
      $summary[] = t('Do not hide seconds.');
    }
  }
}