You are here

public static function YamlFormTime::validateYamlFormTime in YAML Form 8

Form element validation handler for #type 'yamlform_time'.

Note that #required is validated by _form_validate() already.

File

src/Element/YamlFormTime.php, line 88

Class

YamlFormTime
Provides a form element for time selection.

Namespace

Drupal\yamlform\Element

Code

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));
}