You are here

class YamlFormTime in YAML Form 8

Same name in this branch
  1. 8 src/Element/YamlFormTime.php \Drupal\yamlform\Element\YamlFormTime
  2. 8 src/Plugin/YamlFormElement/YamlFormTime.php \Drupal\yamlform\Plugin\YamlFormElement\YamlFormTime

Provides a form element for time selection.

$form['time'] = array(
  '#type' => 'time',
  '#title' => $this
    ->t('Time'),
  '#default_value' => '12:00 AM',
);

Plugin annotation

@FormElement("yamlform_time");

Hierarchy

Expanded class hierarchy of YamlFormTime

1 #type use of YamlFormTime
YamlFormTime::form in src/Plugin/YamlFormElement/YamlFormTime.php
Gets the actual configuration form array to be built.

File

src/Element/YamlFormTime.php, line 23

Namespace

Drupal\yamlform\Element
View source
class YamlFormTime extends FormElement {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = get_class($this);
    return [
      '#input' => TRUE,
      '#theme' => 'input__time',
      '#process' => [
        [
          $class,
          'processYamlFormTime',
        ],
      ],
      '#pre_render' => [
        [
          $class,
          'preRenderYamlFormTime',
        ],
      ],
      '#element_validate' => [
        [
          $class,
          'validateYamlFormTime',
        ],
      ],
      '#theme_wrappers' => [
        'form_element',
      ],
      '#time_format' => 'H:i',
      '#size' => 10,
      '#maxlength' => 10,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    if ($input === FALSE) {

      // Set default value using GNU PHP date format.
      // @see https://www.gnu.org/software/tar/manual/html_chapter/tar_7.html#Date-input-formats.
      if (!empty($element['#default_value'])) {
        $element['#default_value'] = date('H:i', strtotime($element['#default_value']));
        return $element['#default_value'];
      }
    }
    return $input;
  }

  /**
   * Processes a time form element.
   *
   * @param array $element
   *   The form element to process. Properties used:
   *   - #time_format: The time format used in PHP formats.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param array $complete_form
   *   The complete form structure.
   *
   * @return array
   *   The processed element.
   */
  public static function processYamlFormTime(&$element, FormStateInterface $form_state, &$complete_form) {

    // Attach JS support for the time field, if we can determine which time
    // format should be used.
    if (!empty($element['#time_format'])) {
      $element['#attached']['library'][] = 'yamlform/yamlform.element.time';
      $element['#attributes']['data-yamlform-time-format'] = [
        $element['#time_format'],
      ];
    }
    return $element;
  }

  /**
   * Form element validation handler for #type 'yamlform_time'.
   *
   * Note that #required is validated by _form_validate() already.
   */
  public static function validateYamlFormTime(&$element, FormStateInterface $form_state, &$complete_form) {
    $has_access = !isset($element['#access']) || $element['#access'] === TRUE;
    $value = $element['#value'];
    if ($value === '') {
      return;
    }
    $time = strtotime($value);
    if ($time === FALSE) {
      if ($has_access) {
        if (isset($element['#title'])) {
          $form_state
            ->setError($element, t('%name must be a valid time.', [
            '%name' => $element['#title'],
          ]));
        }
        else {
          $form_state
            ->setError($element);
        }
      }
      return;
    }
    $name = empty($element['#title']) ? $element['#parents'][0] : $element['#title'];
    $time_format = !empty($element['#time_format']) ? $element['#time_format'] : DateFormat::load('html_time')
      ->getPattern();

    // Ensure that the input is greater than the #min property, if set.
    if ($has_access && isset($element['#min'])) {
      $min = strtotime($element['#min']);
      if ($time < $min) {
        $form_state
          ->setError($element, t('%name must be on or after %min.', [
          '%name' => $name,
          '%min' => date($time_format, $min),
        ]));
      }
    }

    // Ensure that the input is less than the #max property, if set.
    if ($has_access && isset($element['#max'])) {
      $max = strtotime($element['#max']);
      if ($time > $max) {
        $form_state
          ->setError($element, t('%name must be on or before %max.', [
          '%name' => $name,
          '%max' => date($time_format, $max),
        ]));
      }
    }
    $form_state
      ->setValueForElement($element, date('H:i:s', $time));
  }

  /**
   * Adds form-specific attributes to a 'date' #type element.
   *
   * @param array $element
   *   An associative array containing the properties of the element.
   *
   * @return array
   *   The $element with prepared variables ready for #theme 'input__time'.
   */
  public static function preRenderYamlFormTime($element) {
    $element['#attributes']['type'] = 'time';
    Element::setAttributes($element, [
      'id',
      'name',
      'type',
      'value',
      'size',
      'min',
      'max',
      'step',
    ]);
    static::setAttributes($element, [
      'form-time',
    ]);
    return $element;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormElement::processAutocomplete public static function Adds autocomplete functionality to elements.
FormElement::processPattern public static function #process callback for #pattern form element property.
FormElement::validatePattern public static function #element_validate callback for #pattern form element property.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. 92
RenderElement::preRenderAjaxForm public static function Adds Ajax information about an element to communicate with JavaScript.
RenderElement::preRenderGroup public static function Adds members of this group as actual elements for rendering.
RenderElement::processAjaxForm public static function Form element processing handler for the #ajax form property. 1
RenderElement::processGroup public static function Arranges elements into groups.
RenderElement::setAttributes public static function Sets a form element's class attribute. Overrides ElementInterface::setAttributes
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
YamlFormTime::getInfo public function Returns the element properties for this element. Overrides ElementInterface::getInfo
YamlFormTime::preRenderYamlFormTime public static function Adds form-specific attributes to a 'date' #type element.
YamlFormTime::processYamlFormTime public static function Processes a time form element.
YamlFormTime::validateYamlFormTime public static function Form element validation handler for #type 'yamlform_time'.
YamlFormTime::valueCallback public static function Determines how user input is mapped to an element's #value property. Overrides FormElement::valueCallback