public function AppointmentCalendarForm::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/ AppointmentCalendarForm.php, line 101
Class
Namespace
Drupal\appointment_calendar\FormCode
public function validateForm(array &$form, FormStateInterface $form_state) {
$values = $form_state
->getValues();
$db_conn = \Drupal::database();
$op = (string) $values['op'];
if ($op == $this
->t('Reset')) {
$form_state
->setRedirect('appointment_calendar.subscribers');
}
if ($op == $this
->t('Submit')) {
$start_date = $values['appointment_from_date']
->getTimestamp();
$end_date = $values['appointment_to_date']
->getTimestamp();
// Getting all dates in between Start and End Dates.
$dates = appointment_calendar_daysbetween($start_date, $end_date);
$check_count = 0;
// Checking for already filled slots.
foreach ($dates as $each_date) {
$date_check = $db_conn
->select('appointment_date', 'ad');
$date_check
->fields('ad', [
'date',
]);
$date_check
->condition('date', $each_date, '=');
$date_result = $date_check
->execute()
->fetchField();
if (!empty($date_result)) {
$check_count++;
$date = date('Y-m-d', $each_date);
$this
->messenger()
->addError($date . ' Already filled');
}
}
if ($check_count > 0) {
$form_state
->setErrorByName('appointment_from_date', t('Verify and try adding again'));
}
// Date Validation.
if ($start_date > $end_date) {
$form_state
->setErrorByName('appointment_to_date', t('End Date Should be greater than Start Date'));
}
if ($start_date < strtotime(date('Y-m-d', time()))) {
$form_state
->setErrorByName('appointment_start_date', t('Start Date Should be greater than Today(s) Date'));
}
$slots = $values['appointment_slot'];
// Time slot and Capacity Validation.
$time_slots_check = [];
for ($i = 1; $i <= $slots; $i++) {
$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 format should be 00:00-00:00 (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.'));
}
// Timeslot Check.
if (empty($time_capacity)) {
$form_state
->setErrorByName('time_slot_' . $i . '_capacity', t('Fill time slot 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.'));
}
}
}
}