You are here

public static function OfficeHoursList::validateOfficeHoursSlot in Office Hours 8

Render API callback: Validates the element.

Implements a callback for _office_hours_elements().

For 'office_hours_slot' (day) and 'office_hours_datelist' (hour) elements. You can find the value in $element['#value'], but better in $form_state['values'], which is set in validateOfficeHoursSlot().

Parameters

$element:

\Drupal\Core\Form\FormStateInterface $form_state:

$complete_form:

File

src/Element/OfficeHoursList.php, line 178

Class

OfficeHoursList
Provides a one-line text field form element for the List Widget.

Namespace

Drupal\office_hours\Element

Code

public static function validateOfficeHoursSlot(&$element, FormStateInterface $form_state, &$complete_form) {
  $error_text = '';

  // Return an array with starthours, endhours, comment.
  $input_exists = FALSE;
  $input = NestedArray::getValue($form_state
    ->getValues(), $element['#parents'], $input_exists);
  $input_exists = TRUE;
  if (OfficeHoursDatetime::isEmpty($input)) {
    return;
  }
  $field_settings = $element['#field_settings'];
  $validate_hours = $field_settings['valhrs'];
  $limit_start = $field_settings['limit_start'];
  $limit_end = $field_settings['limit_end'];
  $start = OfficeHoursDatetime::get($input['starthours'], 'Hi');
  $end = OfficeHoursDatetime::get($input['endhours'], 'Hi');

  // If any field of slot is filled, check for required time fields.
  $required_start = $field_settings['required_start'] ?? FALSE;
  if ($required_start && empty($start)) {
    $error_text = 'Opening hours must be set.';
    $erroneous_element =& $element['starthours'];
  }
  $required_end = $field_settings['required_end'] ?? FALSE;
  if ($required_end && empty($end)) {
    $error_text = 'Closing hours must be set.';
    $erroneous_element =& $element['endhours'];
  }
  if ($validate_hours) {
    if ((!empty($start) xor !empty($end)) && !empty($limit_end)) {
      $error_text = 'Both Opening hours and Closing hours must be set.';
      $erroneous_element =& $element;
    }
    elseif ($end < $start && $end == '0000') {

      // Exception: end time is 00:00 / 24:00.
      $error_text = 'Closing hours are earlier than Opening hours.';
      $erroneous_element =& $element;
    }
    elseif (!empty($limit_start) || !empty($limit_end)) {
      if ($start && $limit_start * 100 > $start || $end && $limit_end * 100 < $end) {
        $error_text = 'Hours are outside limits ( @start - @end ).';
        $erroneous_element =& $element;
      }
    }
  }
  if ($error_text) {
    $day_name = OfficeHoursDateHelper::weekDays(FALSE)[$input['day']];
    $error_text = $day_name . ': ' . t($error_text, [
      '@start' => $limit_start . ':00',
      '@end' => $limit_end . ':00',
    ], [
      'context' => 'office_hours',
    ]);
    $form_state
      ->setError($erroneous_element, $error_text);
  }
}