Skip to content
thesnowmonk.com

thesnowmonk.com

Servicenow Tips, Tricks and More.

Menu
  • Home
  • About
  • Contact Us
Menu

Unlocking Efficiency: Harnessing the Power of Code Reusability with UI Scripts for Seamless Development in ServiceNow

Posted on September 23, 2022July 9, 2023 by Arun

Here’s a cool little reusable snippet from my experiments with UI Script. The use case I was dealing with was toggling the visibility of a couple of variables for a catalog item. Now I had to build this particular solution since I was dealing with close to a 100 variables and setting up UI policies for each and every variable was close to impossible. So here’s a reusable little piece of code you can use to achieve the same.

function SampleApplicationUtil() {
  this.vendorMasterList = ['app_1','app_2','app_3','app_4','app_5',
						'app_6','app_7','app_8','app_9','app_10'];
}

SampleApplicationUtil.prototype.getExclusionList = function(apps) {
  	var subsetSet = {};

	// Create a hash map of the subset elements for efficient lookup
	for (var i = 0; i < apps.length; i++) {
		subsetSet[apps[i]] = true;
	}

	var exclusionList = [];

	// Iterate over the superset array and check if each element is in the subset hash map
	for (var j = 0; j < this.vendorMasterList.length; j++) {
		if (!subsetSet[this.vendorMasterList[j]]) {
			exclusionList.push(this.vendorMasterList[j]);
		}
	}

	return exclusionList;
};

SampleApplicationUtil.prototype.setReadOnly = function(g_form, app, val) {
  g_form.setReadOnly(app, val);
};

SampleApplicationUtil.prototype.setVisible = function(g_form, app, val) {
	g_form.setVisible(app, val);
}

SampleApplicationUtil.prototype.setCheckBox = function(g_form, app, val) {
	g_form.setValue(app, val);
}

SampleApplicationUtil.prototype.processExclusionList = function(g_form, apps) {
	for(var i = 0; i < apps.length; i++) {
		this.setCheckBox(g_form, apps[i], false);
		this.setVisible(g_form, apps[i], false);
	}
}

SampleApplicationUtil.prototype.processInclusionList = function(g_form, apps) {
	for(var i = 0; i < apps.length; i++) {
		this.setCheckBox(g_form, apps[i], true);
		this.setVisible(g_form, apps[i], true);
	}
}

Now, the usage is pretty simple. In your UI policy or client script you can invoke the code as follows,

var sau = new SampleApplicationUtil();
var inclusionList = ['app_1', 'app_3', 'app_5'];
var exclusionList = vru.getExclusionList(inclusionList);
sau.processExclusionList(g_form, exclusionList);
sau.processInclusionList(g_form, inclusionList);

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

About This Site

This site is developed and maintained by a ServiceNow developer just like you! An ardent snowhead who is giving you tried and tested tips, tricks and other snippets to get you ahead of the game.

©2025 thesnowmonk.com | Built using WordPress and Responsive Blogily theme by Superb