OnSubmit client script validation to update a list collector variable records before submit

Somujit1
Tera Contributor

 

Hello Experts,

 

I have a requirement to remove the user names from a list collector variable, if a match is found within a array.

 

Scenario and Requirement -

1. In the contact table, there is a Expiry Date field (u_expiry_date), which stores the date value only. It is a Date type field

2. In a catalog item,

- there is a List Collector variable - User Name (user_name)

- there are two Date/Time variables - Start Date (start_date) and End Date (end_date).

 

While submitting the catalog item, the below validation is required -

1. If any of the selected user value in the user_name variable, has u_expiry_date >= start_date and u_expiry_date value <= end_date, those matching user name should be removed from the selected user values and continue to keep the selected user values which donot match the above criteria, before the request submission.

2. Display one alert message to be displayed as '<User1>, <User2>,....<User n> is past the expiry date and has been removed from the User Name field'.

 

I have written the below script include and OnSubmit client script, but it is not working as required 

 

Script Include -

var validateExpired = Class.create();
validateExpired.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getExpiredUser: function() {
        var userName = this.getParameter('sysparm_user');
        gs.info(userName);
        var StartDate = this.getParameter('sysparm_startdate');
        gs.info(StartDate);
        var EndDate = this.getParameter('sysparm_enddate');
        gs.info(EndDate);
        var expiredNoArray = [];
        var validateUser = new GlideRecord('customer_contact');
        validateUser.addEncodedQuery('sys_idIN' + userName);
        validateUser.query();
        while (validateUser.next()) {
            var expiryDate = validateUser.getDisplayValue("u_expiry_date");
            gs.info(expiryDate);
            if (expiryDate >= StartDate && expiryDate <= EndDate) {
                gs.info('Enters if loop');
                var results = {
                    "sys_id": validateUser.getValue("sys_id"),
                    "name": validateUser.getValue("name")
                };
            }
            expiredNoArray.push(results);
            gs.info('Returned result is: ' + results);
        }
        if (expiredNoArray.length > 0) {
            gs.info('Array count is: ' + expiredNoArray.length);
            return JSON.stringify(expiredNoArray);
        } else {
            gs.info('no records returned');
            return;
        }
    },
    type: 'validateExpired'
});

 

Catalog Client Script -

function onSubmit() {
var userName = g_form.getValue('user_name');
alert('User ID is: ' + userName);
var startDateTime = g_form.getDisplayValue('start_date');
alert('Start Time is: ' + startDateTime);
var startSection = startDateTime.split(' ');
var startDate = startSection[0];
alert('Start Date is: ' + startDate);
var endDateTime = g_form.getDisplayValue('end_date');
alert('End Time is: ' + endDateTime);
var endSection = endDateTime.split(' ');
var endDate = endSection[0];
alert('End Date is: ' + endDate);
var checkInductionStat = new GlideAjax('validateExpired');
checkInductionStat.addParam('sysparm_name', 'getExpiredUser');
checkInductionStat.addParam('sysparm_user', userName);
checkInductionStat.addParam('sysparm_startdate', startDate);
checkInductionStat.addParam('sysparm_enddate', endDate);
checkInductionStat.getXMLAnswer(returnUserInfo);
return false;
}

function returnUserInfo(answer) {
if (answer) {
alert('Validated User is: ' + answer);
var valueToValidate = JSON.parse(answer);
for (var i = 0; i < valueToValidate.length; i++) {
var userID = valueToValidate[i].sys_id;
alert('Value to validate is: ' + userID);
var userArray = [];
userArray.push(userID.toString());
var arrayResult = JSON.stringify(userArray);
alert('Array Result is: ' + arrayResult);
var userIDRemove = JSON.parse(arrayResult);
alert('Visitor ID remove is: ' + userIDRemove);
for (var j = 0; j < userIDRemove.length; j++) {
alert('Visitor Id Length is: ' + userIDRemove.length);
var userList = g_form.getValue('user_name');
var listName = userList.split(',');
alert('User Count is: ' + listName.length);
alert('Current list name is: ' + listName);
var index = listName.indexOf(userIDRemove[j]);
alert('Index count is: ' + index);
if (index !== -1) {
alert('Enters if to validate ' + valueToValidate[i].name);
listName.splice(0, 1);
}
}
}
}
alert(valueToValidate[i].name + ' is past the expiry date and has been removed from the User Name field');
var updatedUserList = listName.join(',');
g_form.setValue('user_name', updatedUserList);
}

 

 

Can you please correct we what I am doing wrong in the above, and help me fix it.

 

Thanks,

Somujit

4 REPLIES 4

dusinm
Kilo Contributor

Hello,

You're on the right track, but there are a few key issues in both your Script Include and Client Script that are breaking the logic:

Replace unescortedVisitor with visitorName, and move results.push(...) inside the if block:
if (expiryDate >= StartDate && expiryDate <= EndDate) {
expiredNoArray.push({
"sys_id": validateUser.getValue("sys_id"),
"name": validateUser.getDisplayValue("name")
});
}

Fix the Client Script:

function onSubmit() {
var userIDs = g_form.getValue('user_name');
var startDate = g_form.getValue('start_date').split(' ')[0];
var endDate = g_form.getValue('end_date').split(' ')[0];

var ga = new GlideAjax('validateExpired');
ga.addParam('sysparm_name', 'getExpiredUser');
ga.addParam('sysparm_visitor', userIDs);
ga.addParam('sysparm_startdate', startDate);
ga.addParam('sysparm_enddate', endDate);
ga.getXMLAnswer(function(response) {
if (response) {
var expired = JSON.parse(response);
var expiredIds = expired.map(u => u.sys_id);
var expiredNames = expired.map(u => u.name);
var remaining = g_form.getValue('user_name').split(',').filter(id => !expiredIds.includes(id));
g_form.setValue('user_name', remaining.join(','));
if (expiredNames.length > 0) {
alert(expiredNames.join(', ') + ' is past the expiry date and has been removed from the User Name field');
}
}
});

return false;
}







Somujit1
Tera Contributor
HI @dusinm ,
 
Thank you for your response.
 
I tried modifying the Script Include and the Catalog client script as suggested by you.
 
It is validating one user at a time  and removing the record (meeting the if condition "expiryDate >= startDate && expiryDate <= endDate") when i click on Submit. 
Example, if my list collector has multiple user names which passes the if condition check, then on first Submit click one user is removed and on second submit click other user is removed. 
Will it be possible to validate and remove all the if condition matching users on a single Submit button click?
 
Also, upon the above validation completion, if my list collector value is left with the user names which do not pass the if condition check , then the request should get submitted, which doesnt seem to happen.
 
Please let me know on how to achieve the above. 
 
Below is the updated code -
 
Script Include -
var validateExpired = Class.create();
validateExpired.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getExpiredUser: function() {
        var userName = this.getParameter('user_name');
        gs.info(userName);
        var StartDate = this.getParameter('sysparm_startdate');
        gs.info(StartDate);
        var EndDate = this.getParameter('sysparm_enddate');
        gs.info(EndDate);
        var expiredNoArray = [];
        var validateUser = new GlideRecord('customer_contact');
        validateUser.addEncodedQuery('sys_idIN' + userName);
        validateUser.query();
        while (validateUser.next()) {
            var expiryDate = validateUser.getDisplayValue("u_expiry_date");
            gs.info(expiryDate);
            if (expiryDate >= StartDate && expiryDate <= EndDate) {
                gs.info('Enters if loop:' + validateUser.getValue('name'));
                expiredNoArray.push({
                    "sys_id": validateUser.getValue("sys_id"),
                    "name": validateUser.getDisplayValue("name")
                });
            }
return JSON.stringify(expiredNoArray);
        }
    },
 
    type: 'validateInductionExpired'
});
 
Catalog Client Script -
 
function onSubmit() {
    var userName = g_form.getValue('user_name');
    alert('Unescorted visitor is: ' + userName);
    var startDate = g_form.getValue('start_date').split(' ')[0];
    alert('Start Date is: ' + startDate);
    var endDate = g_form.getDisplayValue('end_date').split(' ')[0];
    alert('End Time is: ' + endDate);
    var checkInductionStat = new GlideAjax('validateExpired');
    checkInductionStat.addParam('sysparm_name', 'getExpiredUser');
    checkInductionStat.addParam('sysparm_visitor', userName);
    checkInductionStat.addParam('sysparm_startdate', startDate);
    checkInductionStat.addParam('sysparm_enddate', endDate);
    checkInductionStat.getXMLAnswer(function(response) {
        if (response) {
            alert('Validated User is: ' + response);
            var valueToValidate = JSON.parse(response);
            var valueToValidateID = valueToValidate.map(u => u.sys_id);
            alert('Value to validate ID: ' + valueToValidateID);
            var valueToValidateNames = valueToValidate.map(u => u.name);
            alert('Value to validate ID: ' + valueToValidateNames);
            var remaining = g_form.getValue('user_name').split(',').filter(id => !valueToValidateID.includes(id));
            alert('Remaining is:' + remaining);
            g_form.setValue('user_name', remaining.join(','));
            if (valueToValidateNames.length > 0) {
                alert(valueToValidateNames.join(',') + ' is past the expiry date and has been removed from the User Name field');
            }
        }
    });
    return false;
}
 
Thanks,
Somujit

alison23taylor
Mega Contributor

The primary problems are: comparing string dates in the Script Include, incorrect placement of results push, and flawed logic in the Client Script for removing users and displaying the alert. You need to parse dates for comparison, collect all results in the loop, and restructure your Client Script to properly update the list collector and alert message after receiving the AJAX response.

palanikumar
Mega Sage

Hi,

In script include, use the datediff function to compare the dates

 if (expiryDate >= StartDate && expiryDate <= EndDate) { should be replaced with following:

 

     if (gs.dateDiff(expiryDate, StartDate) >=0 && gs.dateDiff(expiryDate,EndDate) <=0) {

Thank you,
Palani