Problem/Motivation
I'm using D10, webform 6.2.2, webform_validation with the patch value-comparison-order-3377606-15.patch applied with composer
I want to check the keys date_d_arrivee & date_de_depart with my content type calendrier_de_reservation fields field_date_arrivee & field_date_depart.
I don't want to the webform to be submitted if its dates are already within selected dates of this content type
Steps to reproduce
Following your great instructions : Adding custom validation rules - Webform Validation hooks -
https://www.drupal.org/node/908600 →
I created a
- modules/custom/booking_validation/booking_validation.info.yml
name: 'Booking Validation'
type: module
description: 'Provides custom validation for booking dates.'
core_version_requirement: ^8 || ^9 || ^10
package: Custom
- modules/custom/booking_validation/booking_validation.module
<?php
/**
* Implements hook_webform_validation().
*/
function booking_validation_webform_validation_handler_info() {
return array(
'booking_validation_validate_booking_dates' => array(
'name' => t('Validate Booking Dates'),
'category' => t('Custom'),
),
);
}
/**
* Custom validation handler to validate booking dates.
*/
function booking_validation_validate_booking_dates($form, &$form_state) {
$start_date = $form_state->getValue('date_d_arrivee');
$end_date = $form_state->getValue('date_de_depart');
// Debug: Print out the start and end dates to ensure they are being retrieved correctly.
\Drupal::logger('booking_validation')->debug('Start Date: @start_date', ['@start_date' => $start_date]);
\Drupal::logger('booking_validation')->debug('End Date: @end_date', ['@end_date' => $end_date]);
// Your validation logic goes here...
if (booking_validation_check_booking_conflict($start_date, $end_date)) {
// Add a validation error.
$form_state->setErrorByName('date_d_arrivee', t('There is a booking conflict. Please choose different dates.'));
}
}
/**
* Function to check for booking conflicts in the database.
*/
function booking_validation_check_booking_conflict($start_date, $end_date) {
// Query the database to check for existing bookings that overlap with the provided dates.
$query = \Drupal::entityQuery('node')
->condition('type', 'calendrier_de_reservation')
->condition('field_date_arrivee', $start_date, '<=')
->condition('field_date_depart', $end_date, '>=')
->range(0, 1)
->count();
$conflicting_bookings = $query->execute();
// If there are conflicting bookings, return TRUE.
return !empty($conflicting_bookings);
}
?>
I added some debug to print in dblog the dates in the form.
enabled my submodule
cleared all caches
filled a 1st form with the dates 29/03/2024 - 02/04/2024
filled a 2nd form with the dates 30/03/2024 - 05/04/2024
the 2nd form was submitted normally
I checked dblog and they were no entries
Where did I go wrong ?
Thanks a lot for your help & advice