You are here

public function AppointmentCalendarEditForm::validateForm in Appointment Calendar 8

Form validation handler.

Parameters

array $form: An associative array containing the structure of the form.

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

Overrides FormBase::validateForm

File

src/Form/AppointmentCalendarEditForm.php, line 105

Class

AppointmentCalendarEditForm

Namespace

Drupal\appointment_calendar\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {
  $values = $form_state
    ->getValues();
  $op = (string) $values['op'];
  if ($op == $this
    ->t('Submit')) {
    $date = $values['appointment_slot_date']
      ->getTimestamp();
    $capacity = appointment_calendar_slot_capacity($date);
    $slots = count((array) json_decode($capacity));
    if (!empty($values['appointment_slot'])) {
      $slots += $values['appointment_slot'];
    }

    // Time slot and Capacity Validation.
    for ($i = 1; $i <= $slots; $i++) {
      $booked_capacity = '';
      $time_slot = $values['time_slot_' . $i];
      $time_capacity = $values['time_slot_' . $i . '_capacity'];
      $regex = '/^(?:[01][0-9]|2[0-3]):[0-5][0-9]-(?:[01][0-9]|2[0-3]):[0-5][0-9]$/';

      // Timeslot.
      if (!preg_match($regex, $time_slot)) {
        $form_state
          ->setErrorByName('time_slot_' . $i, t('Time slot should be in between 00:00-23:59 (in between 24 hrs)'));
      }

      // Slot Capacity.
      if ($time_capacity < 0) {
        $form_state
          ->setErrorByName('time_slot_' . $i . '_capacity', t('Slot Capacity should be greater than 0'));
      }
      $booked_capacity = appointment_calendar_slot_capacity_value($date, $time_slot);
      if ($time_capacity < $booked_capacity) {
        $form_state
          ->setErrorByName('time_slot_' . $i, t('Already :slots Appointment(s) booked in this Slot. So it should not be less than :slots', [
          ':slots' => $booked_capacity,
        ]));
      }

      // Checking duplicate slots.
      $time_slots_check[] = $time_slot;
      $vals = array_count_values($time_slots_check);
      if ($vals[$time_slot] > 1) {
        $form_state
          ->setErrorByName('time_slot_' . $i, t('Time slot cannot redeclare twice or more.'));
      }
    }
  }
}