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 user 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 catalog 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

7 REPLIES 7

Ankur Bawiskar
Tera Patron
Tera Patron

@Somujit1 

you should use onChange catalog client script on list collector and inform which user fails the validation

Ask user to remove that value

OR

You can remove that user from list collector and set it again

Remember it doesn't go in loop as you will be setting the list collector and it will trigger the onChane

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Hi @Ankur Bawiskar ,

 

Thanks for your response. 

Is it that this validation check cannot be achieved for onSubmit scenario then?

 

Thanks

@Somujit1 

You can but logically it makes sense to show real-time validation and inform user to remove that value from list collector.

if you want to do onSubmit then why not remove the unwanted users from list collector after RITM is submitted via after insert BR or workflow run script or flow designer, whatever you are using.

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

@Somujit1 

remember these points:

1) Asynchronous GlideAjax won't work as by the time ajax function returns the value your form will get submitted

2) Synchronous GlideAjax is not allowed in portal and scoped application

Refer this link

How to limit the total quantity of a shopping cart for a specific service catalog item in New York v...

Refer these links for workaround/solution on how to use Synchronous GlideAjax in onSubmit

How To: Async GlideAjax in an onSubmit script

Asynchronous onSubmit Catalog/Client Scripts in ServiceNow

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader