You are here

public static function WebformTime::valueCallback in Webform 8.5

Same name and namespace in other branches
  1. 6.x src/Element/WebformTime.php \Drupal\webform\Element\WebformTime::valueCallback()

Determines how user input is mapped to an element's #value property.

Parameters

array $element: An associative array containing the properties of the element.

mixed $input: The incoming input to populate the form element. If this is FALSE, the element's default value should be returned.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Return value

mixed The value to assign to the element.

Overrides FormElement::valueCallback

File

src/Element/WebformTime.php, line 46

Class

WebformTime
Provides a webform element for time selection.

Namespace

Drupal\webform\Element

Code

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'])) {
      try {

        // Evaluate if the value can be time formatted, including relative
        // values like 'now' or '+2 hours'.
        new \DateTime($element['#default_value']);
      } catch (\Exception $exception) {
        \Drupal::messenger()
          ->addError($exception
          ->getMessage());
        return NULL;
      }
      $element['#default_value'] = static::formatTime('H:i', strtotime($element['#default_value']));
      return $element['#default_value'];
    }
    else {
      return NULL;
    }
  }
  return $input;
}