Date/Time field values is switching back and forth on form

TerryC03
Tera Expert

Hello,

 

I have a catalog client script that is using a script include to check for weekends and holidays between the hours of 8 - 5 (8-5 weekdays excluding holidays calendar). If the client script receives an answer of true from the glideAjax, it has detected a weekend or holiday, and moves the date by one until the glideAjax returns false. However, if I wanted to then select manually another weekday, the value in the fields constantly switches between the old value and the newly selected value. If I select another value while this is happening it switches through those values as well. How may I prevent this.

 

Client script:

function onChange(control, oldValue, newValue, isLoading) {
    // Check if the form is loading or the newValue is empty, then exit
    if (isLoading || newValue === '') {
        return;
    }

    // Get the selected date from the 'access_start_date' field
    var selectedDateTime = g_form.getValue('access_start_date');
    
    // Convert the selected date into a JavaScript Date object
    var currentDate = new Date(selectedDateTime);

    // Function to format date to 'yyyy-MM-dd HH:mm:ss'
    function formatDate(date) {
        return date.getFullYear() + '-' +
            ('0' + (date.getMonth() + 1)).slice(-2) + '-' +
            ('0' + date.getDate()).slice(-2) + ' ' +
            ('0' + date.getHours()).slice(-2) + ':' +
            ('0' + date.getMinutes()).slice(-2) + ':' +
            ('0' + date.getSeconds()).slice(-2);
    }

    // Function to call GlideAjax and validate the date
    function validateAndAdjustDate(date) {
        var ga = new GlideAjax('DateValidator');
        ga.addParam('sysparm_name', 'validateDate');
        ga.addParam('selectedDate', formatDate(date));

        ga.getXMLAnswer(function(response) {
            var answer = response;

            if (answer === "true") { // If the date is a holiday or weekend
                g_form.addErrorMessage('The selected date falls on a non-working day (weekend or holiday). Adding one day.');

                // Add one day to the date
                date.setDate(date.getDate() + 1);

                // Call the function again with the updated date to validate it
                validateAndAdjustDate(date);
            } else {
                // When Script Include returns false, meaning the date is valid, update the field
				//g_form.clearValue('access_start_date');
               g_form.setValue('access_start_date', formatDate(date));
            }
        });
    }
    // Start the validation process by checking the selected date
    validateAndAdjustDate(currentDate);
}
1 ACCEPTED SOLUTION

Here's a simplified client script and the script include to show the approach

function onChange(control, oldValue, newValue, isLoading) {
    // Check if the form is loading or the newValue is empty, then exit
    if (isLoading || newValue === '') {
        return;
    }

    var ga = new GlideAjax('DateValidator');
    ga.addParam('sysparm_name', 'validateDate');
    ga.addParam('selectedDate', newValue);
    ga.getXMLAnswer(function(response) {
        if (response != newValue) { // If the date is a holiday or weekend
           	g_form.setValue('access_start_date', response);
		}
	});
}
var DateValidator = Class.create();
DateValidator.prototype = Object.extendsObject(AbstractAjaxProcessor, {

    validateDate: function() {
        var selectedDateStr = this.getParameter('selectedDate'); // Get date from the client
        var selectedDate = new GlideDateTime(selectedDateStr); // Convert to GlideDateTime 

		var output = this._checkHoliday(selectedDate, "8-5 weekdays excluding holidays");
		gs.info("DateValidator: " + selectedDate + " Holiday is: " + output );
		while (output == 'true') {
			selectedDate.addDays(1);
			output = this._checkHoliday(selectedDate, "8-5 weekdays excluding holidays");
		} 

		return output;
    }, 

    _checkHoliday: function(myDateTime, scheduleName) {
		var blockedDay = 'false'; // initalize holiday to false
        var schedule = new GlideRecord('cmn_schedule');
        schedule.addQuery('name', scheduleName);
        schedule.query();
        if (schedule.next()) {
            var sched = new GlideSchedule(schedule.sys_id);
            var d = new GlideDateTime();
            d.setDisplayValue(myDateTime); // setting myDateTime 
            if (sched.isInSchedule(d))
                blockedDay = myDateTime; // not a holiday or weekend
            else
                blockedDay = 'true'; // holiday or weekend
        }
		
		return blockedDay;

    },
});

View solution in original post

5 REPLIES 5

Brad Bowman
Kilo Patron
Kilo Patron

Is this script running onChange of the 'access_start_date' variable? A simpler approach may be to get rid of the functions, passing the selectedDateTime to the Script Include, letting it return a date - either the same one, if it was valid, or the next working day, then set the value of 'access_start_date' only if it is different than selectedDateTIme.

Yes. The access start date is running on the onChange client script. I'll study more on glideAjax and share my results. Or are you saying I can just using this script to run the validation check and pass the datetime via glideAjax?

Pass the newValue via the GlideAjax, then compare to the schedule and use GlideDateTime methods to add a day.  If you return the displayValue of the resulting date, you're only updating the variable once, then without the other functions it will be easier to see what's going on if it isn't as expected.   

From a script include perspective, I'm lost on how to do that (or it's just not coming to me at the moment.) This is the script include I have.

 

var DateValidator = Class.create();
DateValidator.prototype = Object.extendsObject(AbstractAjaxProcessor, {

    validateDate: function() {
        var selectedDateStr = this.getParameter('selectedDate'); // Get date from the client
        var selectedDate = new GlideDateTime(); // Convert to GlideDateTime 

		var output = this._checkHoliday(selectedDateStr, "8-5 weekdays excluding holidays");
		//gs.info("DateValidator: " + selectedDateStr + " Holiday is: " + output );
		return output;
    },
    _checkHoliday: function(myDateTime, scheduleName) {
		var blockedDay = false; // initalize holiday to false
        var schedule = new GlideRecord('cmn_schedule');
        schedule.addQuery('name', '8-5 weekdays excluding holidays');
        schedule.query();
        if (schedule.next()) {
            var sched = new GlideSchedule(schedule.sys_id);
            var d = new GlideDateTime();
            d.setDisplayValue(myDateTime); // setting myDateTime 
            if (sched.isInSchedule(d))
                blockedDay = false; // not a holiday or weekend
            else
                blockedDay = true; // holiday or weekend
        }
		
		return blockedDay;

    },
});