Snippets Collections
var limit = null; //Integer or null
wipeEmployeeIDHRProfile(); // Remove employee Number for 'resetting' profiles for full pull
updateEmployeeNumbersHRProfile(limit); // Set employee number - for coalesce change on transform maps

function updateEmployeeNumbersHRProfile(limit) {
	var count = 0;
	var gr = new GlideRecord('sys_user');
	if(limit) gr.setLimit(limit);
	gr.query();
	while (gr.next()) {
		var employeeID = gr.user_name.toString(); // 'ND23858';
		if(isValid(employeeID)) {
			var firstTwo = employeeID.substring(0,2);
			var lastChars = employeeID.substring(2);

			if(isAlphaOrParen(firstTwo) && isNumeric(lastChars)) {
				updateEmployeeNumberByUser(gr.sys_id, lastChars);
				count++;
			}
			//else gs.info('EMPID | Bad Employee ID: ' + employeeID);
		} //else gs.info('EMPID | Bad Employee ID (not valid): ' + employeeID);

	}
	gs.info('EMPID | Total Count: ' + count);
}

function updateEmployeeNumberByUser(user, employeeID) {
	var gr = new GlideRecord("sn_hr_core_profile");
	gr.addQuery("user", user);
	gr.query();
	if (gr.next()) {
		gr.employee_number = employeeID;
		gr.autoSysFields(false);
		gr.setWorkflow(false);
		gr.update();
	}
}

function wipeEmployeeIDHRProfile() {
	var count = 0;
	var gr = new GlideRecord("sn_hr_core_profile");
	gr.addEncodedQuery("employee_number!=NULL");
	gr.query();
	while (gr.next()) {
		gr.employee_number = null;
		gr.autoSysFields(false);
		gr.setWorkflow(false);
		gr.update();
		count++;
	}
	gs.info('EMPID | Wiped HR Profile Employee IDs: ' + count);
}

function isAlphaOrParen(str) {
	return /^[a-zA-Z()]+$/.test(str);
}

function isNumeric(str) {
	if (typeof str != "string") return false; // we only process strings!  
	return !isNaN(str) && !isNaN(parseFloat(str)); // ...and ensure strings of whitespace fail
}

function isValid(str){
	if(str.indexOf('-') != -1 || str.indexOf('.') != -1)
		return false;
	else return true;
}
new GlideQuery('sys_user')
    .select('company$DISPLAY')
    .forEach(function (user) {
        gs.info(user.company$DISPLAY);
    });

// ACME North America
// ServiceNow
// ...
​//Search a value with incorrect spaces.. 

var input = 'gu ara nteed rate';
var table = 'core_company';
var field = 'name';

var searchName = input.replace(/\s/g, '').toLowerCase();
var gr = new GlideRecord(table);
gr.addEncodedQuery(field + 'ISNOTEMPTY');
gr.query();
while (gr.next()) {
  	var fieldString = gr.getValue(field).replace(/\s/g, '').toLowerCase();
 
    if (fieldString.indexOf(searchName) != -1)
        gs.info('FOUND: "' + gr[field].getDisplayValue() + '"');
}
/*
Example:

2021-03-15T18:05:40.674Z: FOUND: "Guaranteed Rate Insurance"
2021-03-15T18:05:40.677Z: FOUND: "Guaranteed Rate, Inc2"
2021-03-15T18:05:40.678Z: FOUND: "Guaranteed Rate, Inc."
2021-03-15T18:05:40.680Z: FOUND: "Guaranteed Rate, Inc"
2021-03-15T18:05:40.682Z: FOUND: "Guaranteed Rate Affinity"

*/
new GlideQuery('sys_user')
    .where('last_name', 'Luddy')
    .selectOne('first_name')
    .ifPresent(function (user) {
       gs.info(user.first_name);
   });
// Fred
// Find user if they exist, otherwise return user with first_name 'Nobody'
var user = new GlideQuery('sys_user')
    .where('last_name', 'Luddy')
    .selectOne('first_name')
    .orElse({ first_name: 'Nobody' });

// Find user, otherwise throw an Error that the user couldn't be found
var user = new GlideQuery('sys_user')
    .where('last_name', 'Luddy')
    .selectOne('first_name')
    .get(); // this method can throw if no record is found

// Does a given user exist? Assign boolean to userExists
var userExists = new GlideQuery('sys_user')
   .where('last_name', 'Luddy')
    .selectOne('first_name')
    .isPresent();
/* This will come in the body at XML but the header will be text/plain, which is why  
all this is happening manually to get this read from the stream.  
*/  
var reqHeaders = request.headers;
gs.info("CPSNS: reqHeaders content-type" + reqHeaders['content-type']);
if (reqHeaders['content-type'] == "text/plain; charset=UTF-8") {
    var stream = request.body.dataStream;
    var reader = new GlideTextReader(stream);
    var input = "";
    var ln = "";
    while ((ln = reader.readLine()) != null) {
        input += ln;
    }
    gs.info("CPSNS: SUB" + input);
} else {
    var body = {};
    var data = request.body.data;

    gs.info("CPSNS: req.body data" + data);

}
var O365OutageSync = Class.create(); 

O365OutageSync.prototype = { 

    initialize: function() { 

    }, 

    refreshO365OutageRecords: function(token){ 

        var date_now = gs.nowDateTime(); 

        var parser = new JSONParser(); 

        var json_responseBody = "failed to load"; 

        try {  

            var r = new sn_ws.RESTMessageV2('Microsoft Azure', 'Get Service Status'); 

            r.setStringParameterNoEscape('TenantID', gs.getProperty('AzureAccessToken.TenantID')); 

            r.setStringParameterNoEscape('Token', token); 

            var response = r.execute(); 

            var httpStatus = response.getStatusCode(); 

            if(httpStatus == '200'){ 

                //Success 

                var str_responseBody = response.getBody(); 

                json_responseBody = parser.parse(str_responseBody); 

            } else { 

                gs.log("Error requesting O365 Service Status.  httpStatus:" + httpStatus); 

            } 

        } catch(ex) { 

            var message = ex.message; 

            gs.log("Error requesting O365 Service Status.  Error Message:" + message); 

        } 

         

        if(json_responseBody != "failed to load"){ 

            for (s = 0; s < json_responseBody.value.length; s++) { 

                //gs.log(json_responseBody.value[s].WorkloadDisplayName + " : " + json_responseBody.value[s].StatusDisplayName); 

                var str_bs_sys_id = ""; 

                 

                //***Create Business Service Record if it does not already exist*** 

                var gr_bs = new GlideRecord('cmdb_ci_service'); 

                gr_bs.addQuery('name', 'O365 - ' + json_responseBody.value[s].WorkloadDisplayName); 

                gr_bs.query(); 

                if(gr_bs.next()){ 

                    str_bs_sys_id = gr_bs.sys_id + ""; 

                } else if (json_responseBody.value[s].IncidentIds.length > 0){ 

                    //Doesnt exist, create it 

                    var gr_new_bs = new GlideRecord('cmdb_ci_service'); 

                    gr_new_bs.initialize(); 

                    gr_new_bs.setValue('name', 'O365 - ' + json_responseBody.value[s].WorkloadDisplayName); 

                    gr_new_bs.setValue('used_for', 'Production'); 

                    str_bs_sys_id = gr_new_bs.insert(); 

                } 

                 

                 

                //***Create Outages for open incidents*** 

                var arr_openOutages = []; 

                for (i = 0; i < json_responseBody.value[s].IncidentIds.length; i++) { 

                    arr_openOutages.push(json_responseBody.value[s].IncidentIds[i]); 

                    var gr_existing_outage = new GlideRecord('cmdb_ci_outage'); 

                    gr_existing_outage.addQuery('u_number',json_responseBody.value[s].IncidentIds[i]); 

                    gr_existing_outage.query(); 

                    if(gr_existing_outage.next()){ 

                        //Set Outage Status for existing Outage Record 

                        switch(json_responseBody.value[s].Status){ 

                            case 'ServiceDegradation': 

                                gr_existing_outage.setValue('type', 'degradation'); 

                                break; 

                            case 'ServiceInterruption': 

                                gr_existing_outage.setValue('type', 'outage'); 

                                break; 

                        } 

                        gr_existing_outage.update(); 

                         

                         

                    } else { 

                        var gr_new_outage = new GlideRecord('cmdb_ci_outage'); 

                        gr_new_outage.initialize(); 

                        gr_new_outage.setValue('u_number', json_responseBody.value[s].IncidentIds[i]); 

                        gr_new_outage.setValue('cmdb_ci', str_bs_sys_id); 

                        gr_new_outage.begin = date_now; 

                         

                        //Set Outage Status for existing Outage Record 

                        switch(json_responseBody.value[s].Status){ 

                            case 'Investigating': 

                                gr_new_outage.setValue('type', 'degradation'); 

                                break; 

                            case 'ServiceDegradation': 

                                gr_new_outage.setValue('type', 'degradation'); 

                                break; 

                            case 'ServiceInterruption': 

                                gr_new_outage.setValue('type', 'outage'); 

                                break; 

                            case 'RestoringService': 

                                gr_new_outage.setValue('type', 'degradation'); 

                                break; 

                            case 'ExtendedRecovery': 

                                gr_new_outage.setValue('type', 'degradation'); 

                                break; 

                            case 'VerifyingService': 

                                gr_new_outage.setValue('type', 'degradation'); 

                                break; 

                        } 

                        gr_new_outage.insert(); 

                    } 

                } 

                     

                     

                //***End Outages for resolved incidents*** 

                //gs.log("Closing incidents for :" + json_responseBody.value[s].WorkloadDisplayName +", cisysid:" + str_bs_sys_id +  "Status:" + json_responseBody.value[s].Status + ", open outages:" + arr_openOutages.join(',')); 

                if(str_bs_sys_id.length > 0){ 

                    var arr_closedcodes = ['ServiceRestored', 'PostIncidentReportPublished', 'ServiceOperational', 'FalsePositive']; 

                    var arrUtil = new ArrayUtil(); 

                    var gr_active_outage = new GlideRecord('cmdb_ci_outage'); 

                    gr_active_outage.addQuery('cmdb_ci', str_bs_sys_id); 

                    gr_active_outage.addNullQuery('end'); 

                    gr_active_outage.query(); 

                    while(gr_active_outage.next()){ 

                        if((arrUtil.indexOf(arr_closedcodes, json_responseBody.value[s].Status) >= 0)||(arrUtil.indexOf(arr_openOutages, gr_active_outage.u_number) < 0)){ 

                            //Service is fully operational. 

                            //Close out all active outages 

                            gr_active_outage.end = date_now; 

                            gr_active_outage.update(); 

                        } else { 

                            

                        } 

                    } 

                } 

            } 

        }         

    }, 

    refreshO365OutageMessages: function(token){ 

        //***Pull Down Outage Messages*** 

        var parser = new JSONParser(); 

        var json_responseBody = "failed to load"; 

        try {  

            var r = new sn_ws.RESTMessageV2('Microsoft Azure', 'Get All Messages'); 

            r.setStringParameterNoEscape('TenantID', gs.getProperty('AzureAccessToken.TenantID')); 

            r.setStringParameterNoEscape('Token', token); 

            var response = r.execute(); 

            var httpStatus = response.getStatusCode(); 

            if(httpStatus == '200'){ 

                //Success 

                var str_responseBody = response.getBody(); 

                json_responseBody = parser.parse(str_responseBody); 

            } else { 

                gs.log("Error requesting O365 Service Messages.  httpStatus:" + httpStatus); 

            } 

        } catch(ex) { 

            var message = ex.message; 

            gs.log("Error requesting O365 Service Messages.  Error Message:" + message); 

        } 

        if(json_responseBody != "failed to load"){ 

            for (i = 0; i < json_responseBody.value.length; i++) { 

                if(json_responseBody.value[i].Messages.length > 0){ 

                    this.updateOutage(json_responseBody.value[i].Id, json_responseBody.value[i].Messages[json_responseBody.value[i].Messages.length-1].MessageText + "<BR><BR><u>Last Updated: " + json_responseBody.value[i].Messages[json_responseBody.value[i].Messages.length-1].PublishedTime + "</u>"); 

                } else { 

                    this.updateOutage(json_responseBody.value[i].Id, json_responseBody.value[i].ImpactDescription); 

                } 

            } 

        } 

    }, 

    updateOutage: function(str_number, str_details){ 

        var gr_outage = new GlideRecord('cmdb_ci_outage'); 

        gr_outage.addQuery('u_number', str_number); 

        gr_outage.query(); 

        if(gr_outage.next()){ 

            gr_outage.setValue('details', str_details); 

            gr_outage.update(); 

        } 

    }, 

    getAzureAPIAccessToken: function(){ 

        var token = ""; 

        try {  

            var r = new sn_ws.RESTMessageV2('Microsoft Azure', 'Get Access Token'); 

            r.setStringParameterNoEscape('ClientSecret', gs.getProperty('AzureAccessToken.ClientSecret')); 

            r.setStringParameterNoEscape('ClientID', gs.getProperty('AzureAccessToken.ClientID')); 

            r.setStringParameterNoEscape('TenantID', gs.getProperty('AzureAccessToken.TenantID')); 

            var response = r.execute(); 

            var httpStatus = response.getStatusCode(); 

            if(httpStatus == '200'){ 

                //Success 

                var str_responseBody = response.getBody(); 

                var parser = new JSONParser(); 

                var json_responseBody = parser.parse(str_responseBody); 

                token = json_responseBody.access_token; 

            } else { 

                gs.log("Error requesting Azure API Token.  httpStatus:" + httpStatus); 

            } 

        } catch(ex) { 

            var message = ex.message; 

            gs.log("Error requesting Azure API Token.  Error Message:" + message); 

        } 

             

        return token; 

    },     

    type: ‘O365OutageSync’ 

}; 

/*
Client callable script include used for filtering sys_user lists
to identify duplication email users
name: duplicateEmail
active: true
client callabe: true
*/
function duplicateEmail() {
    var xx = new GlideAggregate('sys_user');
    xx.addAggregate('COUNT', 'email');
    xx.addHaving('COUNT', 'email', '>', '1');
    xx.query();
    var answer = new Array();
    while (xx.next()) {
        answer.push(xx.getValue('email'));
    }
    return answer;
}
I have seen few questions wherein users require a VIP Icon for catalog variable when the user is a VIP user..

Use case: Consider you have a Variable which refers to "sys_user" table. When the Request Item form loads or Catalog Task form loads and if the User variable holds a VIP User then vip icon should be visible besides the variable.

Approach:

1) Create an onLoad Catalog Client Script which is set to "Applies on Requested Items" and "Applies on Catalog Tasks"

2) Use Script mentioned below; ensure you give question value in script inside the Contains filter and not the name. Using g_form.getControl() doesn't work on sc_req_item and sc_task tables.

3) Ensure Isolate Script field is set to False for the above Catalog Client Script; this field can be edited from List

Script:

function onLoad() {
	//Type appropriate comment here, and begin script below
	var user = g_form.getReference('user', callBackMethod);
}

function callBackMethod(user){

	if(user.vip.toString() == 'true'){
		var variableQuestionValue = 'User';
		$j("<img src='images/icons/vip.gif'>" ).insertAfter("span.sn-tooltip-basic:contains(" + variableQuestionValue + ")");
	}
}
Screenshots:

1) Variable Question with Value as User being used inside the script



2) Catalog Client Script: Isolate Script -> False



3) RITM Form when User is VIP showing the icon



4) TASK Form when User is VIP showing the icon



5) User "Abel Tuter" is VIP User



Note: If you would like to test this; try changing the value to a user who is not VIP and the icon should not show up

Additionally you can also highlight the background in red/orange color as below

g_form.getDisplayBox('user').style.backgroundColor =  'orange';
You can also show the text in red color as below

g_form.getDisplayBox('user').style.color= 'red';
Thanks for reading the blog and do provide your inputs/suggestions if any.
Fear Not; There is a Better Workaround
...and I do mean workaround. This is by no means to be considered a fix. The secret is in the browser cookies. We know that many plugins contain UI Scripts. These applications are updated from time to time (including the UI Scripts) and that works fine. What's the difference? Activating a plugin triggers a forced cache update for the users' browsers. The difference is that updating a UI Script doesn't trigger this. Not even a cache.do triggers it. It simply forces the server to update cache. Installing/updating plugins seems to be the sole trigger that forces the browser to ask the server for updated cache for UI Scripts.

So how do you force this cache update?
The check for building new cache in this instance is controlled by a cookie on the client browser that ServiceNow creates. The cookie is controlled by a property in ServiceNow called glide.lastupdate. To force this update to happen, all you have to do is set that property to a newer dateTime than it currently is (e.g. the current timestamp). You can do this manually, but that can also be a form of kicking the can down the road. You will be back here soon. At Walmart, we wrote a Business Rule to update this whenever a ui_script is updated:

(function executeRule(current, previous /*null when async*/) {
	
	var gdt = new Date();
	var gdtString = gdt.toString().replace(/ /g,'_').replace(/:/g,'_');
	var timeZone = gdtString.replace(/.*[(](.*)[)].*/,'$1');
	var dateFinal = gdtString.slice(0,25) + timeZone;
	gs.addInfoMessage('System Property glide.lastplugin updated. ' + 
					  'Please be sure to push this updated property with the rest of your code. ' +
					  'This will ensure that the JavaScript cache is updated on the client browser.');
	gs.setProperty('glide.lastplugin', dateFinal);
	
})(current, previous);
I have attached an export of this business rule for any who are interested. The info message reminds developers to ensure this updated property is included in their update set, since business rules are not triggered on update commit.


User Object Cheat Sheet
N

o matter what system you’re working in, it is always critical to be able to identify information about the user who is accessing that system. Being able to identify who the user is, what their groups and/or roles are, and what other attributes their user record has are all important pieces of information that allow you to provide that user with a good experience (without giving them information they don’t need to have or shouldn’t have). ServiceNow gives administrators some pretty simple ways to identify this information in the form of a couple of user objects and corresponding methods. This article describes the functions and methods you can use to get information about the users accessing your system.



GlideSystem User Object

The GlideSystem (gs) user object is designed to be used in any server-side JavaScript (Business rules, UI Actions, System security, etc.). The following table shows how to use this object and its corresponding functions and methods.

Function/Method	Return Value	Usage
gs.getUser()	Returns a reference to the user object for the currently logged-in user.	var userObject = gs.getUser();
gs.getUserByID()	Returns a reference to the user object for the user ID (or sys_id) provided.	var userObject = gs.getUser().getUserByID('employee');
gs.getUserName()	Returns the User ID (user_name) for the currently logged-in user.
e.g. 'employee'	var user_name = gs.getUserName();
gs.getUserDisplayName()	Returns the display value for the currently logged-in user.
e.g. 'Joe Employee'	var userDisplay = gs.getUserDisplayName();
gs.getUserID()	Returns the sys_id string value for the currently logged-in user.	var userID = gs.getUserID();
getFirstName()	Returns the first name of the currently logged-in user.	var firstName = gs.getUser().getFirstName();
getLastName()	Returns the last name of the currently logged-in user.	var lastName = gs.getUser().getLastName();
getEmail()	Returns the email address of the currently logged-in user.	var email = gs.getUser().getEmail();
getDepartmentID()	Returns the department sys_id of the currently logged-in user.	var deptID = gs.getUser().getDepartmentID();
getCompanyID()	Returns the company sys_id of the currently logged-in user.	var companyID = gs.getUser().getCompanyID();
getCompanyRecord()	Returns the company GlideRecord of the currently logged-in user.	var company = gs.getUser().getCompanyRecord();
getLanguage()	Returns the language of the currently logged-in user.	var language = gs.getUser().getLanguage();
getLocation()	Returns the location of the currently logged-in user.	var location = gs.getUser().getLocation();
getDomainID()	Returns the domain sys_id of the currently logged-in user (only used for instances using domain separation).	var domainID = gs.getUser().getDomainID();
getDomainDisplayValue()	Returns the domain display value of the currently logged-in user (only used for instances using domain separation).	var domainName = gs.getUser().getDomainDisplayValue();
getManagerID()	Returns the manager sys_id of the currently logged-in user.	var managerID = gs.getUser().getManagerID();
getMyGroups()	Returns a list of all groups that the currently logged-in user is a member of.	var groups = gs.getUser().getMyGroups();
isMemberOf()	Returns true if the user is a member of the given group, false otherwise.	Takes either a group sys_id or a group name as an argument.

if(gs.getUser().isMemberOf(current.assignment_group)){
//Do something...
}

var isMember = gs.getUser().isMemberOf('Hardware');

To do this for a user that isn't the currently logged-in user...

var user = 'admin';
var group = "Hardware";
if (gs.getUser().getUserByID(user).isMemberOf(group)){
gs.log( gr.user_name + " is a member of " + group);
}

else{
gs.log( gr.user_name + " is NOT a member of " + group);
}
gs.hasRole()	Returns true if the user has the given role, false otherwise.	if(gs.hasRole('itil')){ //Do something... }
gs.hasRole()	Returns true if the user has one of the given roles, false otherwise.	if(gs.hasRole('itil,admin')){
//If user has 'itil' OR 'admin' role then Do something...
}
hasRoles()	Returns true if the user has any roles at all, false if the user has no role (i.e. an ess user).	if(!gs.getUser().hasRoles()){
//User is an ess user...
}
It is also very simple to get user information even if the attribute you want to retrieve is not listed above by using a ‘gs.getUser().getRecord()’ call as shown here…

//This script gets the user's title
gs.getUser().getRecord().getValue('title');


g_user User Object

The g_user object can be used only in UI policies and Client scripts. Contrary to its naming, it is not truly a user object. g_user is actually just a handful of cached user properties that are accessible to client-side JavaScript. This eliminates the need for most GlideRecord queries from the client to get user information (which can incur a fairly significant performance hit if not used judiciously).

g_user Property or Method	Return value
g_user.userName	User name of the current user e.g. employee
g_user.firstName	First name of the current user e.g. Joe
g_user.lastName	Last name of the current user e.g. Employee
g_user.userID	sys_id of the current user e.g. 681ccaf9c0a8016400b98a06818d57c7
g_user.hasRole()	True if the current user has the role specified, false otherwise. ALWAYS returns true if the user has the 'admin' role.

Usage: g_user.hasRole('itil')
g_user.hasRoleExactly()	True if the current user has the exact role specified, false otherwise, regardless of 'admin' role.

Usage: g_user.hasRoleExactly('itil')
g_user.hasRoles()	True if the current user has at least one role specified, false otherwise.

Usage: g_user.hasRoles('itil','admin')
It is often necessary to determine if a user is a member of a given group from the client as well. Although there is no convenience method for determining this from the client, you can get the information by performing a GlideRecord query. Here’s an example…

//Check to see if assigned to is a member of selected group
var grpName = 'YOURGROUPNAMEHERE';
var usrID = g_form.userID; //Get current user ID
var grp = new GlideRecord('sys_user_grmember');
grp.addQuery('group.name', grpName);
grp.addQuery('user', usrID);
grp.query(groupMemberCallback);
   
function groupMemberCallback(grp){
//If user is a member of selected group
    if(grp.next()){
        //Do something
        alert('Is a member');
    }
    else{
        alert('Is not a member');
    }
}
To get any additional information about the currently logged-in user from a client-script or UI policy, you need to use a GlideRecord query. If at all possible, you should use a server-side technique described above since GlideRecord queries can have performance implications when initiated from a client script. For the situations where there’s no way around it, you could use a script similar to the one shown below to query from the client for more information about the currently logged in user.

//This script gets the user's title
var gr = new GlideRecord('sys_user');
gr.get(g_user.userID);
var title = gr.title;
alert(title);


Useful Scripts

There are quite a few documented examples of some common uses of these script methods. These scripts can be found on the ServiceNow wiki.
var gr = new GlideRecord('sc_item_option_mtom');
gr.addQuery('sc_item_option.item_option_new.name','item_name');
gr.addQuery('sc_item_option.value','item_value');
gr.query();

while (gr.next()) {
       gs.addInfoMessage(gr.request_item.number);
}

PSA: How to View Variables in Lists
by 
Bradford Shelley
 Forum Level 2
created 4y ago (edited 3y ago ) in Developer Community
After having to play around with variables quite a bit in a recent project, I thought I'd share how to display variables on a list of Requested Items / Catalog Tasks. This applies to lists and related lists, as reports have their own method of displaying variables. Important note: This was performed on Fuji. Your experience may differ on older versions of ServiceNow.

Step 1 Identify the variables you'd like to display on your list, then copy the sys_id for each variable. This is as simple as heading to the Catalog Item, and jumping into the variable(s) in question. We'll need the sys_id to add the column into the list.

Step 2 Head over to System UI -> Lists

Step 3 Identify the list you'd like to display the variable(s) on. We're looking for one of two things here. Either the name of the view of the list you'd like to include the variable(s) on (I highly recommend creating a new view instead of using the Default view for this, as most likely the variables will apply to certain catalog items instead of every single one), or for a related list look at the Parent and Relationship columns for the table and name of the tab for the related list. Head into the list when you've found it.



Step 4 Create a new List Element(s) from the related list at, using "variables.sys_id" (no quotes) in the actual Element field on the List Element form. Create a new List Element for each variable you wish to add.



Step 5 Head over to the list where variables were just added. They won't show up immediately, so don't panic. Edit the list layout, and move around the variables to the spots you'd like them in the list (even if the position is already how you'd like it, move a variable one position up/down, then move it back and save). At this point, the variables should be visible!

Hope this helps at least one person out there. Take care!
this.XMLHelper = (new x_hca2_mh_intg.MHXMLUtils());

var responseBody = response.getBody();
var prettyXML = this.XMLHelper.prettifyXML(responseBody);


var MHXMLUtils = Class.create();
MHXMLUtils.prototype = {

    initialize: function() {
    },

    parseXMLNode: function (xml, node) {
        var xmlDoc = new XMLDocument2();
        xmlDoc.parseXML(xml);
        return (xmlDoc.getNodeText(node));
    },

    prettifyXML: function (xmlString) {
        var formatted = '';
        var reg = /(>)(<)(/)/g;
        xmlString = xmlString.replace(reg, '$1\r\n$2$3');
        var pad = 0;
        var nodes = xmlString.split('\r\n');
        nodes.forEach(function(node, index) {
            var indent = 0;
            if (node.match( /.+</\w[^>]>$/ ))
                indent = 0;
            else if (node.match( /^</\w/ )) {
                if (pad != 0) {
                    pad -= 1;
                }
            } else if (node.match( /^<\w[^>][^/]>.$/ ))
                indent = 1;
            else
                indent = 0;

            var padding = '';
            for (var i = 0; i < pad; i++)
                padding += '    ';

            formatted += padding + node + '\r\n';
            pad += indent;
        });
        return formatted;
    },

    type: 'MHXMLUtils'
};
star

Tue Aug 31 2021 14:58:18 GMT+0000 (Coordinated Universal Time) https://siteonedev.service-now.com/sys_script_fix.do?sys_id

#siteone #servicenow
star

Thu Mar 18 2021 19:56:16 GMT+0000 (Coordinated Universal Time) https://developer.servicenow.com/blog.do?p=/post/glidequery-p5/

#servicenow
star

Mon Mar 15 2021 18:06:36 GMT+0000 (Coordinated Universal Time)

#servicenow #search #javascript
star

Thu Feb 18 2021 19:29:02 GMT+0000 (Coordinated Universal Time) https://developer.servicenow.com/blog.do?p

#servicenow #glidequery #javascript
star

Thu Feb 18 2021 19:28:38 GMT+0000 (Coordinated Universal Time) https://developer.servicenow.com/blog.do?p

#glidequery #servicenow #javascript
star

Mon Feb 01 2021 21:22:08 GMT+0000 (Coordinated Universal Time) https://developer.servicenow.com/blog.do?p

#servicenow #content #type #plain #text
star

Tue Jan 26 2021 15:41:52 GMT+0000 (Coordinated Universal Time) https://community.servicenow.com/community?id

#servicenow #javascript #duplicate
star

Tue Jan 12 2021 18:21:41 GMT+0000 (Coordinated Universal Time) https://community.servicenow.com/community?id

#servicenow #variables #vip #icon #catalog #client #script
star

Tue Dec 22 2020 18:09:41 GMT+0000 (Coordinated Universal Time) https://community.servicenow.com/community?id=community_article&sys_id=0eb79438db0e93804fc2f4621f961918

#servicenow #ui #script #uiscript
star

Fri Dec 11 2020 17:35:23 GMT+0000 (Coordinated Universal Time) https://servicenowguru.com/scripting/user-object-cheat-sheet/

#servicenow #user #object
star

Wed Dec 09 2020 18:03:53 GMT+0000 (Coordinated Universal Time) https://community.servicenow.com/community?id

#servicenow #inboundemailactions
star

Thu Nov 19 2020 21:32:35 GMT+0000 (Coordinated Universal Time) https://community.servicenow.com/community?id

#servicenow #catalog #servicecatalog #variables #list #listview #view
star

Fri Oct 23 2020 17:42:22 GMT+0000 (Coordinated Universal Time)

#prettyprint #xml #pretty #print #servicenow

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension