datetime_extras-8.x-1.x-dev/src/Plugin/Field/FieldWidget/TimeOnlyWidget.php

src/Plugin/Field/FieldWidget/TimeOnlyWidget.php
<?php

namespace Drupal\datetime_extras\Plugin\Field\FieldWidget;

use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Security\TrustedCallbackInterface;
use Drupal\datetime\Plugin\Field\FieldWidget\DateTimeDefaultWidget;

/**
 * Default widget for time only field.
 *
 * @FieldWidget(
 *   id = "time_only_field_default",
 *   label = @Translation("Time only widget"),
 *   field_types = {
 *     "time_only_field"
 *   }
 * )
 */
class TimeOnlyWidget extends DateTimeDefaultWidget implements TrustedCallbackInterface {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element = parent::formElement($items, $delta, $element, $form, $form_state);

    $date_type = 'none';
    $time_type = 'time';
    $date_format = $this->dateStorage->load('html_date')->getPattern();
    $time_format = '';

    $element['value'] = array_merge($element['value'], [
      '#date_date_format' => $date_format,
      '#date_date_element' => $date_type,
      '#date_time_format' => $time_format,
      '#date_time_element' => $time_type,
      '#date_date_callbacks' => [],
      '#date_time_callbacks' => [
        [static::class, 'timeCallback'],
      ],
    ]);

    return $element;
  }

  /**
   * Callback to add element validator.
   */
  public static function timeCallback(array &$element, FormStateInterface $form_state, ?DrupalDateTime $date = NULL): void {
    $validators = $element['#element_validate'] ?? [];
    $validators = array_merge(
      [[static::class, 'timeValidator']],
      $validators
    );
    $element['#element_validate'] = $validators;
  }

  /**
   * Validator to add the date object.
   */
  public static function timeValidator(array &$element, FormStateInterface $form_state, array &$complete_form): void {
    $time = $element['#value']['time'] ?? NULL;
    if ($time) {
      // Upstream's class only adds the data object on dates, not on time only.
      // This fixes that oversight by adding the date object. If it isn't added,
      // then validation won't pass.
      $form_state->setValue(array_merge($element['#parents'], ['object']), new DrupalDateTime($time, $element['#date_timezone']));
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function trustedCallbacks(): array {
    return [
      'timeCallback',
    ];
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc