You are here

class Duration in Duration Field 8

Provides a duration form element.

Plugin annotation

@FormElement("duration");

Hierarchy

Expanded class hierarchy of Duration

5 string references to 'Duration'
DurationField::propertyDefinitions in src/Plugin/Field/FieldType/DurationField.php
Defines field item properties.
DurationFieldAccessTest::createDefaultSetup in tests/src/Functional/DurationFieldFunctionalTest.php
Sets up a date.
DurationWidget::settingsForm in src/Plugin/Field/FieldWidget/DurationWidget.php
Returns a form to configure settings for the widget.
duration_field.data_types.schema.yml in config/schema/duration_field.data_types.schema.yml
config/schema/duration_field.data_types.schema.yml
duration_field.schema.yml in config/schema/duration_field.schema.yml
config/schema/duration_field.schema.yml
2 #type uses of Duration
DurationWidget::formElement in src/Plugin/Field/FieldWidget/DurationWidget.php
Returns the form for a single field widget.
DurationWidget::settingsForm in src/Plugin/Field/FieldWidget/DurationWidget.php
Returns a form to configure settings for the widget.

File

src/Element/Duration.php, line 15

Namespace

Drupal\duration_field\Element
View source
class Duration extends FormElement {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = get_class($this);
    return [
      '#input' => TRUE,
      '#tree' => TRUE,
      '#granularity' => 'y:m:d:h:i:s',
      // Required elements should be in the format y:m:d:h:i:s.
      '#required_elements' => '',
      '#element_validate' => [
        [
          $class,
          'validateElement',
        ],
      ],
      '#pre_render' => [
        [
          $class,
          'preRenderElement',
        ],
      ],
      '#process' => [
        'Drupal\\Core\\Render\\Element\\RenderElement::processAjaxForm',
        [
          $class,
          'processElement',
        ],
      ],
      '#theme_wrappers' => [
        'form_element',
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    if ($input !== FALSE && !is_null($input)) {
      return DurationService::convertValue($input);
    }
    return NULL;
  }

  /**
   * {@inheritdoc}
   */
  public static function processElement(&$element, FormStateInterface $form_state, &$complete_form) {
    $granularity = explode(':', $element['#granularity']);
    $required_elements = explode(':', $element['#required_elements']);
    $value = FALSE;
    if (isset($element['#value']) && $element['#value']) {
      $value = new \DateInterval($element['#value']);
    }
    $time_mappings = [
      'y' => [
        'label' => t('Years'),
        'key' => 'year',
      ],
      'm' => [
        'label' => t('Months'),
        'key' => 'month',
        'format' => 'm',
      ],
      'd' => [
        'label' => t('Days'),
        'key' => 'day',
      ],
      'h' => [
        'label' => t('Hours'),
        'key' => 'hour',
      ],
      'i' => [
        'label' => t('Minutes'),
        'key' => 'minute',
      ],
      's' => [
        'label' => t('Seconds'),
        'key' => 'second',
      ],
    ];

    // Create a wrapper for the elements. This is done in this manner
    // rather than nesting the elements in a wrapper with #prefix and #suffix
    // so as to not end up with [wrapper] as part of the name attribute
    // of the elements.
    $div = '<div';
    $classes = [
      'duration-inner-wrapper',
    ];
    if (!empty($element['#states'])) {
      drupal_process_states($element);
    }
    foreach ($element['#attributes'] as $attribute => $attribute_value) {
      if (is_string($attribute_value)) {
        $div .= ' ' . $attribute . "='" . $attribute_value . "'";
      }
      elseif ($attribute == 'class') {
        $classes = array_merge($classes, $attribute_value);
      }
    }
    $div .= ' class="' . implode(' ', $classes) . '"';
    $div .= '>';
    $element['wrapper_open'] = [
      '#markup' => $div,
      '#weight' => -1,
    ];
    foreach ($time_mappings as $key => $info) {
      if (preg_grep('/' . $key . '/i', $granularity)) {
        $element[$info['key']] = [
          '#id' => $element['#id'] . '-' . $info['key'],
          '#type' => 'number',
          '#title' => $info['label'],
          '#value' => $value ? $value
            ->format('%' . $key) : 0,
          '#required' => preg_grep('/' . $key . '/i', $required_elements) ? TRUE : FALSE,
          '#weight' => 0,
          '#min' => 0,
        ];
        if (!empty($element['#ajax'])) {
          $element[$info['key']]['#ajax'] = $element['#ajax'];
        }
      }
    }
    $element['wrapper_close'] = [
      '#markup' => '</div>',
      '#weight' => 1,
    ];

    // Attach the CSS for the display of the output.
    $element['#attached']['library'][] = 'duration_field/element';
    return $element;
  }

  /**
   * Prepares the element for rendering.
   *
   * @param array $element
   *   An associative array containing the properties of the element. Properties
   *   used: #title, #value, #description, #size, #placeholder, #required,
   *   #attributes.
   *
   * @return array
   *   The $element with prepared values ready for rendering
   */
  public static function preRenderElement(array $element) {

    // Set the wrapper as a container to the inner values.
    $element['#attributes']['type'] = 'container';
    Element::setAttributes($element, [
      'id',
      'name',
      'value',
    ]);
    static::setAttributes($element, [
      'form-duration',
    ]);
    return $element;
  }

  /**
   * Sets the value of the submitted element.
   */
  public static function validateElement(&$element, FormStateInterface $form_state, $form) {
    $mappings = [
      'year' => 'Y',
      'month' => 'M',
      'day' => 'D',
      'hour' => 'H',
      'minute' => 'M',
      'second' => 'S',
    ];
    $values = [];
    foreach ($mappings as $key => $duration_key) {
      if (isset($element[$key])) {
        $values[$key] = $element[$key]['#value'];
      }
    }
    $form_state
      ->setValue($element['#parents'], DurationService::convertValue($values));
  }

}

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
Duration::getInfo public function Returns the element properties for this element. Overrides ElementInterface::getInfo
Duration::preRenderElement public static function Prepares the element for rendering.
Duration::processElement public static function
Duration::validateElement public static function Sets the value of the submitted element.
Duration::valueCallback public static function Determines how user input is mapped to an element's #value property. Overrides FormElement::valueCallback
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.