Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

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

@Somujit1 

Hope you are doing good.

Did my reply answer your question?

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

JackieZhang
Tera Contributor

Please refer to this code:

 

/** Retrieve the specified param's value from the URL **/
function getParmVal(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}

function linkToEvamThenSubmit() {
    var evamID = getParmVal('evam');
    var evamIDIsValid = evamID != null && evamID.length > 0;

    if (evamIDIsValid && g_form.mandatoryCheck()) {
        //Show a loading dialog while the async call is made
        var loadingDialog = new GlideDialogWindow("dialog_loading", true);
        loadingDialog.setPreference('table', 'loading');
        loadingDialog.setTitle('Loading...');
        loadingDialog.render();
        var bundleID = g_form.getUniqueValue();

        var ga = new GlideAjax('global.EvamLinkingService');
        ga.addParam('sysparm_name', 'linkConfigBundleToEvam');
        ga.addParam('sysparm_evam_id', evamID);
        ga.addParam('sysparm_bundle_id', bundleID);
        ga.getXML(function(response) {
            var answer = response.responseXML.documentElement.getAttribute("answer");
            if (answer == 'ok') {
                gsftSubmit(null, g_form.getFormElement(), 'sysverb_insert');
            } else {
                g_form.addErrorMessage(getMessage('Sorry, something went wrong linking the Config bundle to the EVAM definition. Please check the logs or try again later.'));
            }
        });
    } else {
        gsftSubmit(null, g_form.getFormElement(), 'sysverb_insert');
    }
}

if (typeof window == 'undefined')
    runPostLinkingActions();

/** Server-side function to insert the current record and navigate an necessary **/
function runPostLinkingActions() {
    current.insert();
    gs.include('ActionUtils');
    var au = new ActionUtils();
    au.postInsert(current);
}

Ashish Parab
Mega Sage
Mega Sage

Hello @Somujit1 ,

 

Recently, I worked on a requirement where I needed to call a script include in an onSubmit client script. I received a response from the Script Include, but my request still submitted without validating.

 

I created a hidden variable and used an onChange client script to store the GlideAjax response in it. Then, I used an onSubmit client script to check the validation. I think this approach might easily work for you too.

 

Please mark this response as Correct and Helpful if it assists you.


Thanks,
Ashish