Catalog client scripts Archives - ServiceNow Guru https://servicenowguru.com/tag/catalog-client-scripts/ ServiceNow Consulting Scripting Administration Development Tue, 28 May 2024 21:47:37 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.2 https://servicenowguru.com/wp-content/uploads/2024/05/cropped-SNGuru-Icon-32x32.png Catalog client scripts Archives - ServiceNow Guru https://servicenowguru.com/tag/catalog-client-scripts/ 32 32 Building a CI Change Calendar Macro – On The Fly https://servicenowguru.com/reporting/ci-change-calendar-macro/ https://servicenowguru.com/reporting/ci-change-calendar-macro/#comments Wed, 20 Jul 2011 12:39:19 +0000 https://servicenowguru.wpengine.com/?p=3920 A co-worker asked me for some help yesterday fulfilling an interesting requirement. He needed to set up a configuration item reference field or catalog variable that would display a calendar macro that, when clicked, would open a popup window containing a change calendar report for that configuration item. I figured this idea might be of

The post Building a CI Change Calendar Macro – On The Fly appeared first on ServiceNow Guru.

]]>
A co-worker asked me for some help yesterday fulfilling an interesting requirement. He needed to set up a configuration item reference field or catalog variable that would display a calendar macro that, when clicked, would open a popup window containing a change calendar report for that configuration item. I figured this idea might be of use to others so I’m posting it here!

CI Change Calendar Report Macro Popup

I’ve written before about UI macros, and different types of popups on SNGuru. I’ve also written about how your change management process can be a valuable input into your other ITIL processes such as incident management. You can refer to those posts if you’re interested in more detail on some of the ideas used in this article.

The real magic of this solution is how you can create this calendar report ‘on-the fly’ simply by constructing the correct URL. This is something that a colleague of mine, Bobby Edmonds, tipped me off to a couple of years ago. The URL contains several ‘sysparm_’ parameters that point to the fields on the report form. Once you know those, you just have to pass them the correct values. The URL for the calendar report needs to look something like this…

sys_report_template.do?sysparm_table=change_request&sysparm_type=calendar&sysparm_cal_field=end_date&sysparm_from_list=true&sysparm_manual_labor=true&sysparm_query=^end_date%3Ejavascript:gs.endOfLastMonth()'^cmdb_ci=YOUR_CI_SYS_ID_HERE
I plan on writing a post about creating on-the-fly reports soon, but you can piece together the necessary URL parameters for a report by poking around any existing report in your system with a DOM inspector to see what parameters are necessary.

You might be asking, “Why don’t you just point directly to the existing change calendar report URL?”. You could certainly do that, and avoid all of the above, but the requirement in this case is to have the calendar report filtered based on the CI chosen in the field, so it needs to be dynamic.

Because this URL will be initiated from a UI macro (for this example) we’ll need to escape the ampersands and you can see that I’ve done that in the code below. The rest of the code is almost identical to the out-of-box ‘user_show_incidents’ UI macro that you see on the incident ‘Caller’ field. Once the URL is constructed we can use ‘popupOpen’ to display the report in a popup!

Your UI macro should look like this. Once set up, it can be added to the CI reference field of your choice by adding the ‘ref_contributions=ci_show_change_calendar’ attribute to the dictionary entry ‘Attributes’ field of that CI reference field.

‘ci_show_change_calendar’ UI macro
Name: ci_show_change_calendar
Description:
Show CI change calendar popup link
Activate by:
– set the active field in this macro to true
– adding the attribute to a dictionary field: ref_contributions=ci_show_change_calendar
Script:

<!--?xml version="1.0" encoding="utf-8" ?-->



<script>
function showCIChangeCalendar(reference) {
   //Construct the calendar report URL
   var url = 'sys_report_template.do?sysparm_table=change_request$[AMP]sysparm_type=calendar$[AMP]sysparm_cal_field=end_date$[AMP]sysparm_from_list=true$[AMP]sysparm_manual_labor=true$[AMP]sysparm_query=^end_date%3Ejavascript:gs.endOfLastMonth()^cmdb_ci=';
   
   var s = reference.split('.');
   var referenceField = s[1];
   var v = g_form.getValue(referenceField);
   url = url + v;
   //Open the popup 
   var features = "width=700,height=650,toolbar=no,status=no,directories=no,menubar=no,resizable=yes,scrollbars=1";
   popupOpen(url, 'show_calendar', 700, 650, features, true);
}
</script>

 

Add a Change Calendar Macro to a Catalog Reference Variable

You can use a similar technique to add a calendar macro icon next to a catalog reference variable. The big, additional challenge in the service catalog is that reference field macros are not supported for catalog variables. In order to add one you have two options. The first would be to create a UI page or UI macro-type variable similar to the example above. The big drawback would be that the icon wouldn’t appear right next to the reference variable without some clever client scripting.
The second option (which I chose) is to use a catalog client script to construct the macro on-the-fly and place it in the correct spot next to the reference field. This technique is based on a previous solution I wrote about in another SNCGuru article about placing macros next to non-reference fields.

Your catalog client script should look like this. Just add the name of your CI reference variable in the ‘ciVarName’ line below.

‘Add CI Change Calendar Macro’ Catalog Client Script
Name: Add CI Change Calendar Macro
Applies to: Catalog item or variable set of your choice
Type: onLoad
Script (Pre-Fuji version):

function onLoad() {
//The reference variable name to put the icon next to
var ciVarName = 'cmdb_ci';//Add the icon decoration to the reference field
var ciEl = 'lookup.' + g_form.getControl(ciVarName).id;
$(ciEl).insert({
after: '<a id="cmdb_ci_calendar_macro" style="padding-right: 4px;"></a><img title="CI Change Calendar" src="images/icons/dayview.gifx" alt="CI Change Calendar" />'
});
//Add the 'onclick' event
$('cmdb_ci_calendar_macro').observe('click', showCIChangeCalendar);

function showCIChangeCalendar(){
//Construct the calendar report URL
var url = 'sys_report_template.do?sysparm_table=change_request&sysparm_type=calendar&sysparm_cal_field=end_date&sysparm_from_list=true&sysparm_manual_labor=true&sysparm_query=^end_date%3Ejavascript:gs.endOfLastMonth()';
if(g_form.getValue(ciVarName) != ''){
url = url + '^cmdb_ci=' + g_form.getValue(ciVarName);
}

//Open the popup
var features = "width=700,height=650,toolbar=no,status=no,directories=no,menubar=no,resizable=yes,scrollbars=1";
popupOpen(url, 'show_calendar', 700, 650, features, true);
}
}

Script (Fuji version):

function onLoad() {
//The reference variable name to put the icon next to
var ciVarName = 'cmdb_ci';

//Add the icon decoration to the reference field
var ciEl = 'lookup.' + g_form.getControl(ciVarName).id;
$(ciEl).insert({
after: '<a id="cmdb_ci_calendar_macro" class="icon-calendar btn btn-default sn-tooltip-basic" style="padding: 6px 10px; vertical-align: text-bottom;" title="" data-original-title="CI Change Calendar"></a>'
});
//Add the 'onclick' event
$('cmdb_ci_calendar_macro').observe('click', showCIChangeCalendar);

function showCIChangeCalendar(){
//Construct the calendar report URL
var url = 'sys_report_template.do?sysparm_table=change_request&sysparm_type=calendar&sysparm_cal_field=end_date&sysparm_from_list=true&sysparm_manual_labor=true&sysparm_query=^end_date%3Ejavascript:gs.endOfLastMonth()';
if(g_form.getValue(ciVarName) != ''){
url = url + '^cmdb_ci=' + g_form.getValue(ciVarName);
}

//Open the popup
var features = "width=700,height=650,toolbar=no,status=no,directories=no,menubar=no,resizable=yes,scrollbars=1";
popupOpen(url, 'show_calendar', 700, 650, features, true);
}
}

When you’re done, your catalog variable will have a calendar link next to it that looks like this…
CI Change Calendar Macro Catalog Variable

The post Building a CI Change Calendar Macro – On The Fly appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/reporting/ci-change-calendar-macro/feed/ 5
Set Default Date/Time Picker Dialog Time https://servicenowguru.com/client-scripts-scripting/set-default-datetime-picker-dialog-time/ https://servicenowguru.com/client-scripts-scripting/set-default-datetime-picker-dialog-time/#comments Tue, 28 Jun 2011 14:39:49 +0000 https://servicenowguru.wpengine.com/?p=3857 H ave you ever wondered how you can change the default time displayed in a Date/Time dialog? In general, the Date/Time dialog is controlled by back-end code so there’s not much you can do with it. I’ve seen this question a few times now so I decided to come up with a solution. Because the

The post Set Default Date/Time Picker Dialog Time appeared first on ServiceNow Guru.

]]>
H

ave you ever wondered how you can change the default time displayed in a Date/Time dialog? In general, the Date/Time dialog is controlled by back-end code so there’s not much you can do with it. I’ve seen this question a few times now so I decided to come up with a solution.

Date Time Picker

Because the Date/Time picker dialog is controlled by back-end code, the only way to change the default time is via client scripting. What I found is that you can run a client script when the dialog comes up and set the hours, minutes, and seconds to whatever you want. The trick is running your client script at the right time. You can’t react to a change or a form submission like you might for regular client scripting scenarios. Instead, you need to react to the click of the calendar icon next to the Date/Time field.

Fortunately, the Prototype library that ships with ServiceNow includes something that does exactly what we need…the Event.observe method. The basic idea behind this method is to wait for a specific event (in this case the ‘onClick’ event from the calendar icon) and then run some code along with that event. I’ve used this method before in an article I wrote about controlling the ordering of client-side code.

Event.observe works by attaching itself to a specific event on a specific element. For the purposes of this solution, we need to find the ‘A’ tag associated with the calendar icon (the element) and check for the ‘click’ event. Then we can run the code to set the time to whatever we want…typically midnight or something similar. Below is a function that does just that. It works for regular forms and for catalog items. You just need to call the function and pass in the name of the Date/Time field or variable like this…

setDatePickerTime('');

…and here’s the ‘setDatePickerTime’ function

function setDatePickerTime(field){
//Attach an event listener to set default time value for date picker
Event.observe($(g_form.getControl(field).id).next('a'), 'click', function() {
setTimeout("$('GwtDateTimePicker_hh').value = '00';$('GwtDateTimePicker_mm').value = '00';$('GwtDateTimePicker_ss').value = '00';",0);
});
}

Here’s an example client script I set up on the Incident form to run onLoad (which will almost always be the case for this script) and attach event listeners to the ‘Opened’ and ‘Closed’ fields so that their time picker would be set to midnignt.

‘Set Date Picker Time’ Client Script
Name: Set Date Picker Time
Table/Catalog Item/Variable Set: Wherever you need it!
Type: OnLoad
Script:

function onLoad() {
//Set the date picker default time to '00' for 'Opened' and 'Closed' fields
setDatePickerTime('opened_at');
setDatePickerTime('closed_at');
}function setDatePickerTime(field){
//Attach an event listener to set default time value for date picker
Event.observe($(g_form.getControl(field).id).next('a'), 'click', function() {
setTimeout("$('GwtDateTimePicker_hh').value = '00';$('GwtDateTimePicker_mm').value = '00';$('GwtDateTimePicker_ss').value = '00';",0);
});
}

The post Set Default Date/Time Picker Dialog Time appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/client-scripts-scripting/set-default-datetime-picker-dialog-time/feed/ 39
Cool Tip! Show and Hide Loading Dialog Frames https://servicenowguru.com/system-ui/show-hide-loading-dialog-frames/ https://servicenowguru.com/system-ui/show-hide-loading-dialog-frames/#comments Tue, 04 Jan 2011 13:36:13 +0000 https://servicenowguru.wpengine.com/?p=3128 Here’s a very cool (and simple) secret that allows you to show and hide loading dialog screens. These scripts can be run from anywhere in your system that supports client-side javascript. You’ve probably seen these used in various places in your ServiceNow instance. To show a loading dialog…
//Show the loading dialog

The post Cool Tip! Show and Hide Loading Dialog Frames appeared first on ServiceNow Guru.

]]>
Here’s a very cool (and simple) secret that allows you to show and hide loading dialog screens. These scripts can be run from anywhere in your system that supports client-side javascript.

You’ve probably seen these used in various places in your ServiceNow instance.

Long Loading Form Dialog

To show a loading dialog…

//Show the loading dialog immediately as the form loads
var loadingDialog = new GlideDialogWindow("dialog_loading", true);
loadingDialog.setPreference('table', 'loading');
loadingDialog.setTitle('Loading...'); //Set the loading dialog title here...
loadingDialog.render();

To hide that same loading dialog…

loadingDialog.destroy();

For a practical example of how this could be used, check out the ‘Restrict Report Table Selection by Role’ article here on SNGuru. That solution requires some pretty heavy client-side Javascript that could take a while to execute in certain circumstances. Because of this, it was important that I let the user know that there was something happening that they needed to wait on.

Another great example is a customization I created to deal with long-loading forms. The customization required that a loading dialog be displayed before the form loaded, and that the loading dialog be destroyed when everything on the form finished.

The post Cool Tip! Show and Hide Loading Dialog Frames appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/system-ui/show-hide-loading-dialog-frames/feed/ 15
Field Styles for Service Catalog Variables https://servicenowguru.com/system-ui/field-styles-service-catalog-variables/ https://servicenowguru.com/system-ui/field-styles-service-catalog-variables/#comments Fri, 03 Dec 2010 14:45:17 +0000 https://servicenowguru.wpengine.com/?p=3012 ServiceNow allows you to modify the CSS style of any field by adding a personalized style. Instructions for performing this customization are outlined on the ServiceNow wiki. There isn’t a built-in way to do this same thing with the fields (variables) in the Service Catalog. Applying styles to service catalog variables is possible however through

The post Field Styles for Service Catalog Variables appeared first on ServiceNow Guru.

]]>
ServiceNow allows you to modify the CSS style of any field by adding a personalized style. Instructions for performing this customization are outlined on the ServiceNow wiki. There isn’t a built-in way to do this same thing with the fields (variables) in the Service Catalog. Applying styles to service catalog variables is possible however through the use of catalog client scripts. This article shows you how.


This customization really boils down to getting the correct input element on the form and applying the correct CSS style. Because this all needs to be done in javascript, the regular CSS rules you’re used to need to be modified a bit. For example, setting a background color on a field needs to be done with ‘backgroundColor’ instead of ‘background-color’. Hyphens are replaced by a camel-case convention for CSS styles.

To get the form element you can simply use ‘g_form.getControl(VARIABLE_NAME)’. Then you simply apply the correct CSS style like this…

//Set the width of a field
g_form.getControl('').style.width = '150px';

Here are some common styles I’ve seen used in the past…

g_form.getControl('').style.width = '150px'; //Set the width of a field
g_form.getControl('').style.backgroundColor = 'LimeGreen'; //Set the background color of a field
g_form.getControl('').style.color = 'blue'; //Set the text color of a field
g_form.getControl('').style.fontStyle = 'italic'; //Set the text font to italic
g_form.getControl('').style.fontWeight = 'bold'; //Set the text font to bold

Reference fields: A special case

One thing to watch out for is reference fields. The ‘control’ element is actually hidden for all reference fields so using the script above on a reference field will set a style, but that style will be set on an element you’ll never see. For reference fields you need to get the ‘sys_display’ input element. Here’s a sample script that shows how you could do this…

var myVar = $('sys_display.' + g_form.getControl('').id); //Get the correct reference element
myVar.style.width = '350px'; //Set the width

Putting it all together

The result in the image above was produced by the following catalog client script…

function onLoad() {
//Set styles for the 'caller_id' variable
var myVar = $('sys_display.' + g_form.getControl('caller_id').id);
myVar.style.width = '350px';
myVar.style.backgroundColor = 'LimeGreen';
myVar.style.color = 'blue';
myVar.style.fontStyle = 'italic';

//Set styles for the 'impact' variable
var myVar2 = g_form.getControl('impact');
myVar2.style.width = '200px';
myVar2.style.backgroundColor = 'yellow';
myVar2.style.color = 'purple';
myVar2.style.fontWeight = 'bold';
}

The post Field Styles for Service Catalog Variables appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/system-ui/field-styles-service-catalog-variables/feed/ 43
Change the Size of a List Collector Slushbucket Variable https://servicenowguru.com/client-scripts-scripting/change-size-list-collector-slushbucket-variable/ https://servicenowguru.com/client-scripts-scripting/change-size-list-collector-slushbucket-variable/#comments Wed, 24 Nov 2010 08:33:06 +0000 https://servicenowguru.wpengine.com/?p=2830 List collector variables are a great way to collect multiple pieces of information about referenced records in a single variable in the Service Catalog. One complaint I get about these variables is that they take up a lot of space on the screen. While there’s not a lot you can do with regular slushbuckets in

The post Change the Size of a List Collector Slushbucket Variable appeared first on ServiceNow Guru.

]]>
List collector variables are a great way to collect multiple pieces of information about referenced records in a single variable in the Service Catalog. One complaint I get about these variables is that they take up a lot of space on the screen. While there’s not a lot you can do with regular slushbuckets in the system, List Collector variables have a little bit more flexibility because they can be manipulated with client scripts. Check out the SNGuru List Collector archives for more examples of cool List Collector modifications you can use.

In this article I’ll show you how you can reclaim some of that Service Catalog screen real estate by modifying the size of a list collector variable using a catalog client script.

Important note!!! Changing the size of your list collector has NO effect on the number of items displayed in that list collector. The number of entries in list collectors in your system is controlled by a global property. You can increase the number of entries in your filter, but that also incurs a performance hit when working with slushbucket filters since that whole number of items needs to be loaded every time in the slushbucket. You really don’t want to increase this number to much more than the default of 100.

The property is called ‘glide.xmlhttp.excessive’ and is documented here. It applies to all slushbuckets in your system (including those for list collectors).

The script is pretty simple. All you need to do is give it the name of the list collector variable you would like to resize, along with the width and height. In my testing I’ve found that the look of the variable can start to get kind of messy if you set a width less than 250 so I wouldn’t go any smaller than that.

As of the Winter 2010 Stable 2 release, it is now possible to hide the filter portion of a list collector variable completely. This can be accomplished by adding the ‘no_filter’ attribute to the ‘Attributes’ field on the variable form.
function onLoad(){
	var varName = 'YOUR_VARIABLE_NAME_HERE';
	var height = '100'; //Optional
	var width = '250'; //Optional
	try{
		//Get the left and right bucket input elements
		var leftBucket = $(varName + '_select_0');
		var rightBucket = $(varName + '_select_1');
		
		//If the element exists
		if(leftBucket){
			//Adjust the bucket height (default is 300px)
			if(height){
				leftBucket.style.height = height + 'px';
				rightBucket.style.height = height + 'px';
			}
			
			if(width){
				//Adjust the bucket width (default is 340px)
				leftBucket.style.width = width + 'px';
				rightBucket.style.width = width + 'px';
                                //Fix Fuji/Geneva width issue
                                leftBucket.up('.slushbucket').style.width = width*2 + 100 + 'px';
			}
			
			//Fix the expanding item preview issue
			$(varName + 'recordpreview').up('td').setAttribute('colSpan', '3');
		}
	}catch(e){}
}

Here’s the result!

The post Change the Size of a List Collector Slushbucket Variable appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/client-scripts-scripting/change-size-list-collector-slushbucket-variable/feed/ 28
Move List Collector Options https://servicenowguru.com/client-scripts-scripting/move-list-collector-options/ https://servicenowguru.com/client-scripts-scripting/move-list-collector-options/#comments Tue, 22 Jun 2010 15:42:14 +0000 https://servicenowguru.wpengine.com/?p=1758 Here’s a cool catalog client script that I figured out for a client. It allows you to move one or more selected options from one side of a list collector variable slushbucket to another. Using the script is pretty straight forward. Just supply the name of the list collector variable you are working with, and

The post Move List Collector Options appeared first on ServiceNow Guru.

]]>
Here’s a cool catalog client script that I figured out for a client. It allows you to move one or more selected options from one side of a list collector variable slushbucket to another. Using the script is pretty straight forward. Just supply the name of the list collector variable you are working with, and then make sure you provide an array of option IDs to move from one side to another. The option IDs need to be added to the ‘selectedIDs’ array in the middle chunk of code. The code below is set up to move ALL options in the right column of a slushbucket to the left.

//Name of variable to move options from
var varName = 'YOUR_VARIABLE_NAME_HERE';
var leftBucket = gel(varName + '_select_0');
var rightBucket = gel(varName + '_select_1');
var selectedOptions = rightBucket.options;

//Get an array of all option IDs to move
var selectedIDs = new Array();
var index = 0;
for(var i = 0; i < selectedOptions.length; i++){
   selectedIDs[index] = i;
   index++;
}

//Move all returned options from right to left bucket and sort the results
//Switch 'rightBucket' and 'leftBucket' to move from left to right
moveSelectedOptions(selectedIDs, rightBucket, leftBucket, '--None--');
//Sort the resultant options in the left bucket
sortSelect(leftBucket);

The post Move List Collector Options appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/client-scripts-scripting/move-list-collector-options/feed/ 35
Limiting Number of Selections in a List Collector https://servicenowguru.com/client-scripts-scripting/limiting-selections-list-collector/ https://servicenowguru.com/client-scripts-scripting/limiting-selections-list-collector/#comments Fri, 18 Jun 2010 13:47:43 +0000 https://servicenowguru.wpengine.com/?p=1743 List collector variables are a great way (currently the only way) to allow a user to select multiple options from a referenced table in a single variable on a service catalog item. The list collector variable allows you to choose from one to many (potentially hundreds or more) selections. What if you wanted to limit

The post Limiting Number of Selections in a List Collector appeared first on ServiceNow Guru.

]]>
List collector variables are a great way (currently the only way) to allow a user to select multiple options from a referenced table in a single variable on a service catalog item. The list collector variable allows you to choose from one to many (potentially hundreds or more) selections. What if you wanted to limit the number of items that a user could select? This script does exactly that. It restricts the selected items list on a list collector variable to whatever amount you choose. Just use the catalog client script below and set the variables for the maximum number of selections and the name of the variable to apply the restriction to.


Limit Selections Catalog Client Script
Name: Limit Selections
Type: onChange
UI type: Desktop
Script:

function onChange(control, oldValue, newValue, isLoading) {
//Limit the number of selected options in a list collector
//Specify the max options and variable name below
var maxOptions = 5;
var varName = 'users';
var leftBucket = gel(varName + '_select_0');
var rightBucket = gel(varName + '_select_1');
var selectedOptions = rightBucket.options;
if(selectedOptions.length > maxOptions){
//Move any options with IDs greater than maxOptions back to left bucket
var selectedIDs = [];
var index = 0;
for(var i = maxOptions; i < selectedOptions.length; i++){
selectedIDs[index] = i;
index++;
}
//Move options and sort the left bucket
moveSelectedOptions(selectedIDs, rightBucket, leftBucket, '--None--');
sortSelect(leftBucket);
alert('You cannot select more than ' + maxOptions + ' options.');
}
}

 

Service Portal version

With the introduction of the Service Portal UI, ServiceNow severely limits the client-side API that is available. That, in addition to the completely different UI of the list collector element itself, requires a different scripting approach. The following script is designed to work as a client script in Service Portal ONLY. Just make sure you change the ‘UI type’ field to ‘Mobile’ for this script.

Limit Selections Catalog Client Script (Service Portal version)
Name: Limit Selections
Type: onChange
UI type: Mobile
Script:

function onChange(control, oldValue, newValue, isLoading) {
//Limit the number of selected options in a list collector
//Specify the max options and variable name below
var maxOptions = 5;
var collectorName = 'users';
var myListCollector = g_list.get(collectorName);
var selectedOptions = g_form.getValue(collectorName).split(',');
if(selectedOptions.length > maxOptions){
//Remove the last item
myListCollector.removeItem(selectedOptions[selectedOptions.length-1]);
g_form.addErrorMessage('You cannot select more than ' + maxOptions + ' options.');
}
}

The post Limiting Number of Selections in a List Collector appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/client-scripts-scripting/limiting-selections-list-collector/feed/ 21
Removing or Disabling Choice List Options https://servicenowguru.com/client-scripts-scripting/removing-disabling-choice-list-options/ https://servicenowguru.com/client-scripts-scripting/removing-disabling-choice-list-options/#comments Wed, 17 Feb 2010 19:24:13 +0000 https://servicenowguru.wpengine.com/?p=950 One common configuration task in ServiceNow is to disable (make read-only) or remove certain select options from a choice list of a particular choice field. By far, the most common scenario where I’ve seen this is when a customer wants to restrict access to some ‘Closed’ type of option in a choice list depending on

The post Removing or Disabling Choice List Options appeared first on ServiceNow Guru.

]]>
One common configuration task in ServiceNow is to disable (make read-only) or remove certain select options from a choice list of a particular choice field. By far, the most common scenario where I’ve seen this is when a customer wants to restrict access to some ‘Closed’ type of option in a choice list depending on the role of the user. This is so common, in fact, that it has been worked into an Incident Management Best Practices plugin. In general, removing or adding choice list options is pretty easy to do, but there are a few things that you need to look out for. Disabling or enabling choice list options is not as simple just because it’s not a built-in function in ServiceNow. In this post, I’ll show you how to do both!

Removing/Adding Options

You can remove options from a choice list by using the following function call…

g_form.removeOption(<fieldName>, <choiceValue>);

Here are a couple of practical examples…

//Remove the 'Critical' priority option when some field changes
function onChange(control, oldValue, newValue, isLoading) {
   g_form.removeOption('priority', '1');
}
If you’re removing options in an ‘onLoad’ script make sure that you only remove the option if it is not the currently selected option as shown here.
//Remove the 'Closed' state option if the user is not an admin and state is not 'Closed'
function onLoad() {
   var isAdmin = g_user.hasRole('admin');
   var state = g_form.getValue('state');
   if (!isAdmin && (state != 7)){
      //alert('Current user is not an admin');
      g_form.removeOption('state', '7');
   }
}

If you want to remove ALL options from a choice list you can use the following…

g_form.clearOptions('<FIELD_NAME>');

Options can be added to a choice list by using the ‘addOption’ function call…

g_form.addOption(<fieldName>, <choiceValue>, <choiceLabel>, <targetIndex>);
Note that the ‘targetIndex’ parameter is a numeric, zero-based value that allows you to specify the point in the choice list where an option should be inserted. So, if you had a choice list with 5 options and you wanted your option to be added as the third option, your target index would be the number 2. If your choice list contains a ‘–None–‘ value, you must include that in your count (usually the 0 index). ‘targetIndex’ is an optional parameter. If no target index is specified, then the option will be added to the end of the choice list.

Here’s an example…

//Add the 'Critical' priority option as the second option (--None-- value is option 1) when some field changes
function onChange(control, oldValue, newValue, isLoading) {
   g_form.addOption('priority', '1', '1 - Critical', 1);
}

Disabling/Enabling Options

There is no out-of-box function provided to disable options in choice lists.

The reason for this is that the Chrome browser didn’t support the method and removed the options instead. It is possible to disable choice list options in other browsers though, but you’ll have to provide the function to do so. In order to do that, you can create a new UI Script by navigating to ‘System UI -> UI Scripts’ and entering the following settings:

UI Script SettingsName: DisableEnableOption (Make sure to avoid any special characters in the naming of UI scripts)
Active: true
Global: true
Script:

function disableOption(fieldName, choiceValue) {
   fieldName = g_form.removeCurrentPrefix(fieldName);
   var control = g_form.getControl(fieldName);
   if (control && !control.options) {
      var name = 'sys_select.' + this.tableName + '.' + fieldName;
      control = gel(name);
   }
   if (!control)
      return;

   if (!control.options)
      return;

   var options = control.options;
   for (var i = 0; i < options.length; i++) {
      var option = options[i];
      if (option.value == choiceValue) {
         control.options[i].disabled = 'true';
         break;
      }
   }
}

function enableOption(fieldName, choiceValue) {
   fieldName = g_form.removeCurrentPrefix(fieldName);
   var control = g_form.getControl(fieldName);
   if (control && !control.options) {
      var name = 'sys_select.' + this.tableName + '.' + fieldName;
      control = gel(name);
   }
   if (!control)
      return;

   if (!control.options)
      return;

   var options = control.options;
   for (var i = 0; i < options.length; i++) {
      var option = options[i];
      if (option.value == choiceValue) {
         control.options[i].disabled = '';
         break;
      }
   }
}

Once you have created your global UI Script functions, you can use it in almost the exact same way as the ‘removeOption’ function above. The only difference is that there is no need to prefix the function call with ‘g_form’.

You can disable options from a choice list by using the following function call…

disableOption(<fieldName>, <choiceValue>);

Here are the same examples from above modified to use the ‘disableOption’ call instead of the ‘g_form.removeOption’ call.

//Disable the 'Critical' priority option when some field changes
function onChange(control, oldValue, newValue, isLoading) {
   disableOption('priority', '1');
}

Again, you probably will only want to disable the option if it is not the option selected when the form loads.

//Disable the 'Closed' state option if the user is not an admin and state is not 'Closed'
function onLoad() {
   var isAdmin = g_user.hasRole('admin');
   var state = g_form.getValue('state');
   if (!isAdmin && (state != 7)){
      //alert('Current user is not an admin');
      disableOption('state', '7');
   }
}

Similarly, you can enable options in a choice list by using the following function call. Since the option is not actually removed from the list, it’s not necessary to provide the choice index.

enableOption(<fieldName>, <choiceValue>);

Here’s an example of the ‘enableOption’ call.

//Enable the 'Critical' priority option when some field changes
function onChange(control, oldValue, newValue, isLoading) {
   enableOption('priority', '1');
}

The post Removing or Disabling Choice List Options appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/client-scripts-scripting/removing-disabling-choice-list-options/feed/ 37
Show/Hide Service Catalog Variable Help Text https://servicenowguru.com/client-scripts-scripting/showhide-service-catalog-variable-help-text/ https://servicenowguru.com/client-scripts-scripting/showhide-service-catalog-variable-help-text/#comments Tue, 02 Feb 2010 14:42:41 +0000 https://servicenowguru.wpengine.com/?p=728 Please note that as of the Istanbul release of ServiceNow there is a variable field setting that allows you to automatically display the help text for a particular variable. The scripts below are still needed to selectively display the help text but the new field is probably the way to go if you’re on Istanbul

The post Show/Hide Service Catalog Variable Help Text appeared first on ServiceNow Guru.

]]>
Please note that as of the Istanbul release of ServiceNow there is a variable field setting that allows you to automatically display the help text for a particular variable. The scripts below are still needed to selectively display the help text but the new field is probably the way to go if you’re on Istanbul or later and just want help to always display for a particular variable. Click this link for more details.

Each Service Catalog variable in ServiceNow allows you to provide the end-user with some additional information about that variable and how to use it. By default, these ‘Help Text’ sections are collapsed when the service catalog item loads. You may want to automatically expand the help text for a particular variable so that it is more obvious to the user what they need to do. Here’s how you can toggle the display of the help text for variables in your service catalog.

Expanded Help Text

The following catalog client script will show the help text for the ‘caller_id’ variable automatically when the catalog item form loads.

function onLoad() {
var myVar = g_form.getControl('caller_id');
toggleHelp(myVar.id);
}

Geneva Workaround!!!
If you’re an early Geneva adopter it looks like ServiceNow has a bug where they’ve broken ‘toggleHelp’ because they’re not targeting the right element ID within their function. Hopefully this will get fixed but until then here’s a workaround using the same example above…

//Geneva workaround because 'toggleHelp' is broken
var myVar = g_form.getControl('caller_id');
var myVarHelp = $('question_help_IO_' + myVar.id.split(':')[1] + '_toggle');
toggleVariableHelpText(myVarHelp);

Note: There are some variable types (I’ve identified labels and multiple choice variables so far) that return an ID prefixed by ‘sys_original.’. For these variables, your catalog client script will have to replace that text in order to work correctly. Here’s an example for a multiple choice variable named ‘multichoice’.

function onLoad() {
var myVar = g_form.getControl('multichoice');
toggleHelp(myVar.id.replace('sys_original.', ''));
}

Switching help text open or closed instead of a toggle

If you encounter a situation where you need to open or close the help text automatically, but don’t know what state the help text will be in, then the ‘toggleHelp’ function probably won’t work for you. This is most often the case if you need to toggle the help text based on some ‘onChange’ event. For those cases you can use the following catalog client scripts, which leverage the ‘expand/collapse’ effect functionality I wrote about.

Expand the help text for a variable (‘caller_id’)

//Expand help text for a variable
var myVar = g_form.getControl('caller_id');
var wrapper = $('help_' + myVar.id + '_wrapper');
var image = $('img.help_' + myVar.id + '_wrapper');
wrapper.style.display = "block";
image.src = "images/filter_reveal16.gifx";
image.alt = getMessage("Display / Hide");
_frameChanged();

Collapse the help text for a variable (‘caller_id’)

//Collapse help text for a variable
var myVar = g_form.getControl('caller_id');
var wrapper = $('help_' + myVar.id + '_wrapper');
var image = $('img.help_' + myVar.id + '_wrapper');
wrapper.style.display = "none";
image.src = "images/filter_hide16.gifx";
image.alt = getMessage("Display / Hide");
_frameChanged();

ServiceNow has changed this…once again…in the Geneva release. Please be aware that these catalog client scripts are prone to break in future releases. I’m only providing them here for those specific cases where the business need outweighs that risk. Here are the working scripts for Geneva and beyond.

Expand the help text for a variable (‘caller_id’) – GENEVA AND BEYOND

//Expand help text for a variable
var myVar = g_form.getControl('caller_id').id;
myVar = myVar.replace(':', '_');
var wrapper = $('question_help_' + myVar + '_toggle_value');
var image = $('question_help_' + myVar + '_toggle');
wrapper.show();
image.addClassName('icon-vcr-down');
image.removeClassName('icon-vcr-right');
_frameChanged();

Collapse the help text for a variable (‘caller_id’) – GENEVA AND BEYOND

//Collapse help text for a variable
var myVar = g_form.getControl('caller_id').id;
myVar = myVar.replace(':', '_');
var wrapper = $('question_help_' + myVar + '_toggle_value');
var image = $('question_help_' + myVar + '_toggle');
wrapper.hide();
image.addClassName('icon-vcr-right');
image.removeClassName('icon-vcr-down');
_frameChanged();

The post Show/Hide Service Catalog Variable Help Text appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/client-scripts-scripting/showhide-service-catalog-variable-help-text/feed/ 57
Changing the Filter of a List Collector Variable via Client Script https://servicenowguru.com/client-scripts-scripting/changing-filter-list-collector-variable-client-script/ https://servicenowguru.com/client-scripts-scripting/changing-filter-list-collector-variable-client-script/#comments Wed, 13 Jan 2010 23:28:22 +0000 https://servicenowguru.wpengine.com/?p=666 If you’ve worked with the Service-now.com service catalog much, you’ve probably realized that there are some differences between the service catalog interface and the traditional forms that are used throughout the rest of the tool. The intention of this is to make the experience a little bit better for end users of the system but

The post Changing the Filter of a List Collector Variable via Client Script appeared first on ServiceNow Guru.

]]>
If you’ve worked with the Service-now.com service catalog much, you’ve probably realized that there are some differences between the service catalog interface and the traditional forms that are used throughout the rest of the tool. The intention of this is to make the experience a little bit better for end users of the system but it also means that you, as an administrator, have to learn a few new tricks to deal with those differences.

One of these differences is the List collector variable. It allows the user to select multiple items from a list of items and optionally filter those items to help in their selection. One of the most common requests I see about this type of variable deals with how to handle the filter at the top of the list collector. Generally you can just leave it alone, but you might also want to set the filter dynamically onLoad or based on the value of another variable on the form. Depending on the situation and the number of items in the list collector table you may want to remove the filter portion completely.

List Collector - Filtered

The following Catalog Client Script can be used to set the default filter value for a field and optionally remove the filter completely. It assumes that your List collector variable is named ‘configuration_items’. By default it sets a filter where ‘name != null’ and ‘sys_class_name (CI type)’ is anything. Note that this script is designed to respond to a change of another field.

Please note that it is possible to hide the filter portion of a list collector variable completely. This can be accomplished by adding the ‘no_filter’ attribute to the ‘Attributes’ field on the variable form. The client script method may still be useful if you want to show/hide the filter conditionally however. This also works for Service Portal! Just make sure you set the ‘UI type’ field on the client script form to ‘Both’.

 

function onChange(control, oldValue, newValue, isLoading) {
//Apply a filter to the list collector variable
var collectorName = 'configuration_items';
var filterString = 'name!=NULL^sys_class_nameANYTHING';

//Try Service Portal method
try{
var myListCollector = g_list.get(collectorName);
myListCollector.reset();
myListCollector.setQuery(filterString);
}
//Revert to Service Catalog method
catch(e){
//Find and hide the filter header elements (optional)
//Simple method for items with only one list collector
//$('ep').select('.row')[0].hide();
//Advanced method for items with more than one list collector (more prone to upgrade failure)
//var el = $('container_' + g_form.getControl(collectorName).id).select('div.row')[0].hide();

//Reset the filter query
window[collectorName + 'g_filter'].reset();
window[collectorName + 'g_filter'].setQuery(filterString);
window[collectorName + 'acRequest'](null);
}
}
Note: If you are trying to filter your list collector in an onLoad script, you have to modify the script so that it waits for the list collector to be rendered before it sets the filter. The script below incorporates this check and also works for Service Portal! Just make sure you set the ‘UI type’ field on the client script form to ‘Both’.
function onLoad() {
//Apply a default filter to the list collector variable
var collectorName = 'configuration_items';
var filterString = 'name!=NULL^sys_class_nameANYTHING';

//Try Service Portal method
try{
var myListCollector = g_list.get(collectorName);
myListCollector.reset();
myListCollector.setQuery(filterString);
}
//Revert to Service Catalog method
catch(e){
//Hide the list collector until we've set the filter
g_form.setDisplay(collectorName, false);
setCollectorFilter();
}

function setCollectorFilter(){
//Test if the g_filter property is defined on our list collector.
//If it hasn't rendered yet, wait 100ms and try again.
if(typeof(window[collectorName + 'g_filter']) == 'undefined'){
setTimeout(setCollectorFilter, 100);
return;
}
//Find and hide the filter elements (optional)
//Simple method for items with only one list collector
//$('ep').select('.row')[0].hide();
//Advanced method for items with more than one list collector (more prone to upgrade failure)
//var el = $('container_' + g_form.getControl(collectorName).id).select('div.row')[0].hide();

//Reset the filter query
window[collectorName + 'g_filter'].reset();
window[collectorName + 'g_filter'].setQuery(filterString);
window[collectorName + 'acRequest'](null);
//Redisplay the list collector variable
g_form.setDisplay(collectorName, true);
}
}

The post Changing the Filter of a List Collector Variable via Client Script appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/client-scripts-scripting/changing-filter-list-collector-variable-client-script/feed/ 120