### Example Usage of getQueryStringParameter
Source: https://servicenowguru.com/client-scripts-scripting/parse-url-parameters-client-script
Demonstrates how to call the getQueryStringParameter function to get the value of the 'sysparm_query' parameter and use it to set a field value.
```javascript
function onLoad(current_sys_id) {
var queryParam = getQueryStringParameter('sysparm_query');
if (queryParam) {
g_form.setValue('short_description', queryParam);
}
}
```
--------------------------------
### Start Next Order Guide Item Script
Source: https://servicenowguru.com/system-definition/order-request-items-order-guide
Use this script in a 'Run script' workflow activity to set the state of the next item in an order guide to 'Work in Progress', initiating its workflow. Ensure the 'Wait for' activity is configured in the next item's workflow. Replace 'Computer Software' with the actual name of the next item.
```javascript
//If item is part of an order guide then start next item(s)
if(!current.order_guide.nil()){ //Change to 'current.request.u_order_guide' for pre-Helsinki
//Start the 'Computer Software' item next
itemStart('Computer Software');
}
function itemStart(nextItemName){
//Query for the item that should start next
var item = new GlideRecord('sc_req_item');
item.addQuery('request', current.request);
item.addQuery('cat_item.name', nextItemName);
item.query();
while(item.next()){
//Set the item to 'Work in Progress' to initiate the item workflow (requires 'Wait for' activity in item workflow)
item.state = 2;
item.update();
}
}
```
--------------------------------
### UI Page Processing Script Example
Source: https://servicenowguru.com/system-ui/glidedial
This example demonstrates how to use values from a UI Page within a server-side processing script. It references a ServiceNow wiki page for detailed instructions.
```javascript
It is described here: http://wiki.servicenow.com/index.php?title=UI_Pages#Using_a_Processing_Script
```
--------------------------------
### Populate Request with Order Guide Variables (Business Rule)
Source: https://servicenowguru.com/system-definition/populate-order-guide-request-ticket
This script attempts to populate the current request record with user-defined variables from an order guide. It's noted that this method may not work as expected because system may not track order guide variables after they are passed to individual items.
```javascript
current.u_order_guide = c.current_guide;
current.short_description = “New Employee Hire Request”;
var notes = “User details”;
notes += “
Name ” + c.current_guide.variables.name;
notes += “
Title ” + c.current_guide.variables.title;
notes += “
Department ” + c.current_guide.variables.department.getDisplayValue();
current.description = notes;
```
--------------------------------
### Catalog Item Image Placement Example
Source: https://servicenowguru.com/system-ui/ui-macros/add-macro-non-reference-field
This snippet refers to an example for correctly setting up image placement on a catalog item. It is located towards the bottom of the linked post and addresses issues with icon positioning.
```html
Towards the bottom you’ll find an example.
```
--------------------------------
### Populate Order Guide Business Rule Script
Source: https://servicenowguru.com/system-definition/populate-order-guide-request-ticket
This script runs before a request is inserted. It queries the cart to determine the current order guide and then checks the order guide's rule base to ensure at least one item from the rule base is included in the cart. If conditions are met, it populates the 'u_order_guide' field on the request.
```javascript
var c = new GlideRecord('sc_cart');
c.get('user', gs.getUserID());
if(c.current_guide){
var isOrderGuide = true;
var foundItemCount = 0;
//Query the order guide rule base
var og = new GlideRecord('sc_cat_item_guide_items');
og.addQuery('guide', c.current_guide);
og.query();
while(og.next()){
var mustHave = false;
var foundItem = false;
//If the condition is empty then item must be ordered
if(og.condition.nil()){
mustHave = true;
}
//Check to see if the rule matches at least one item in the cart
var itm = new GlideRecord('sc_cart_item');
itm.addQuery('cart', c.sys_id);
itm.addQuery('cat_item', og.item.sys_id.toString());
itm.query();
if(itm.hasNext()){
foundItem = true;
foundItemCount++;
}
if(mustHave && !foundItem){
//Do not update order guide
isOrderGuide = false;
break;
}
}
if(isOrderGuide && foundItemCount > 0){
//If actual order guide items are included populate the order guide field
current.u_order_guide = c.current_guide;
}
}
```
--------------------------------
### Populate Order Guide Field via Business Rule
Source: https://servicenowguru.com/system-definition/populate-order-guide-request-ticket
Use this business rule on the sc_request table before insert to populate the 'u_order_guide' field by retrieving the user's current cart and its associated guide. This method is safer as it avoids modifying out-of-box code.
```javascript
var c = new GlideRecord('sc_cart');
c.get('user', gs.getUserID());
current.u_order_guide = c.current_guide;
```
--------------------------------
### Transform Map onComplete Script Example
Source: https://servicenowguru.com/imports/simplifying-data-imports-parties
Example of an onComplete transform script that compiles exceptions from the import set log and queues a system event to notify the user.
```javascript
// Example of onComplete script logic
// var exceptions = log.getExceptions(); // Hypothetical method to get logged exceptions
// var notificationText = 'Import completed with the following exceptions:\n' + exceptions;
// gs.eventQueue('IMPORT_COMPLETE_NOTIFICATION', current, gs.getUserID(), notificationText); // Queues a system event
```
--------------------------------
### Example of Configured Attributes Field
Source: https://servicenowguru.com/system-definition/condition-builder-attributes-that-pack-a-punch
This example shows a fully configured Attributes field on a dictionary record with multiple condition builder options enabled. The order of attributes does not affect functionality.
```text
condition_builder=v2,show_condition_count=true,readable=true,no_truncate=true,allow_related_list_query=true
```
--------------------------------
### Populate Variable in Service Catalog Order Guide
Source: https://servicenowguru.com/service-now-general-knowledge/populating-default-values-url-module
Demonstrates an attempt to populate a variable ('requested_for') in a Service Catalog order guide via URL. Note: sysparm_query is not directly supported for service catalog items.
```URL
service-now.com/com.glideapp.servicecatalog_cat_item_guide_view.do?sysparm_initial=true&sysparm_guide=37c517ae0a0a0a6a00c2ee57a47ebddf&sysparm_query=requested_for=odonohus
```
--------------------------------
### Instantiate _CIUtils_2
Source: https://servicenowguru.com/cmdb/walking-servicenowcom-cmdb-relationship-tree
Demonstrates how to create an instance of the _CIUtils_2 Script Include for use in scripts.
```javascript
var ciu = new _CIUtils_2();
```
--------------------------------
### Get Distinct Operating Systems with GlideAggregate
Source: https://servicenowguru.com/scripting/gliderecord-distinct-query
Use GlideAggregate with groupBy to get a distinct list of operating systems and their counts from the cmdb_ci_server table. Requires no special setup.
```javascript
var gr = new GlideAggregate('cmdb_ci_server'); //GlideAggregate query
gr.addAggregate('count'); //Count aggregate (only necessary for a count of items of each OS)
gr.orderByAggregate('count'); //Count aggregate ordering
gr.groupBy('os'); //Group aggregate by the 'os' field
gr.query();
while(gr.next()){
var osCount = gr.getAggregate('count'); //Get the count of the OS group
//Print the OS name and count of items with that OS
gs.print('Distinct operating system: ' + gr.os + ': ' + osCount);
}
```
--------------------------------
### Solving Client Script 'Before and After' Problem
Source: https://servicenowguru.com/category/client-scripts-scripting/page/2
Addresses the 'before and after' execution problem in client scripts. This example demonstrates how to manage script execution order.
```javascript
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}
//Type appropriate comment here, and then write the code
}
```
--------------------------------
### Get Form Control Element
Source: https://servicenowguru.com/system-ui/field-styles-service-catalog-variables
A basic example to retrieve a form control element using its name, which can then be styled.
```javascript
var el = g_form.getControl('comments');
```
--------------------------------
### Basic Loading Dialog Example
Source: https://servicenowguru.com/system-ui/show-hide-loading-dialog-frames
This client script demonstrates the basic usage of showLoadingDialog() and hideLoadingDialog() to display a loading indicator while performing form operations. It's important to ensure the dialog has enough time to render before being hidden.
```javascript
function onLoad() {
//Type appropriate comment here, and begin script below
showLoadingDialog();
g_form.setDisplay('category', false);
// alert('Hello');
g_form.setDisplay('category', true);
// alert('Hello2');
var s = 3;
s=s*1000;
var a=true;
var n=new Date();
var w;
var sMS=n.getTime();
while(a){
w=new Date();
wMS=w.getTime();
if(wMS-sMS>s) a=false;
}
hideLoadingDialog();
}
```
--------------------------------
### Create Welcome UI Page
Source: https://servicenowguru.com/system-ui/service-portalstyle-homepage-widgets
This HTML and CSS defines the 'welcome_to_servicenow' UI page. It includes styling for quick links and a welcome message. Modify as needed for custom layouts and branding.
```html
Welcome to ServiceNow!
Order Something
Browse the catalog for services and items you need
Knowledge Base
Browse and search for articles, rate or submit feedback
Report an Issue
Contact support to make a request, or report a problem
Live Chat
Start a chat conversation with customer service agents
```
--------------------------------
### Get Current User Object
Source: https://servicenowguru.com/scripting/user-object-cheat-sheet
Retrieves a reference to the user object for the currently logged-in user. Use this as a starting point for accessing other user attributes.
```javascript
var userObject = gs.getUser();
```
--------------------------------
### Instantiate GlideSchedule with sys_id
Source: https://servicenowguru.com/business-rules-scripting/schedule-time-addition
This code snippet shows how to get a GlideRecord for a schedule and then instantiate a GlideSchedule object using its sys_id. This is a common setup for schedule-based calculations.
```javascript
var schedRec = new GlideRecord('cmn_schedule');
schedRec.get('sys_id', '090eecae0a0a0b260077e1dfa71da828');
var sched = new GlideSchedule(schedRec.sys_id);
```
--------------------------------
### Initialize and Add Groups to Search Summary
Source: https://servicenowguru.com/system-ui/custom-global-search-page
Initializes the IRQuerySummary and adds specified groups to the summary based on user preferences. This prepares the search results summary.
```Jelly
if (typeof GlideIRQuerySummary != 'undefined')
var summarizer = GlideIRQuerySummary.get();
else
var summarizer = Packages.com.glide.db.ir.IRQuerySummary.get();
${sysparm_tsgroups}
var seeGroup = gs.getPreference('ts.group.${jvar_ts_groupid}','true') == 'true';
summarizer.addGroup('${jvar_ts_groupid}', '$[jvar_query_orig]');
```
--------------------------------
### Get User Sys ID from Updated By Field
Source: https://servicenowguru.com/system-ui/add-user-profile-photo-to-form
This example demonstrates how to retrieve a user's Sys ID based on who last updated a record. It shows how to get the User ID from the sys_updated_on field and use it to look up the user's Sys ID. This is useful for dynamically displaying the most recent commenter's photo.
```JavaScript
gs.getUser().getUserByID('user_name_from_sys_updated_on').getID()
```
--------------------------------
### Execute CompanyTwo API Integration
Source: https://servicenowguru.com/scripting/implementing-a-factory-pattern-on-servicenow
This is an example of how to initiate the integration logic for CompanyTwo. Ensure the CompanyTwoAPI script include is correctly defined.
```javascript
new CompanyTwoAPI().execute()
```
--------------------------------
### Construct Catalog Item URL with Parameters
Source: https://servicenowguru.com/scripting/client-scripts-scripting/parse-url-parameters-client-script
Example of constructing a URL for a catalog item, including parameters for category and comments.
```javascript
var url = 'com.glideapp.servicecatalog_cat_item_view.do?sysparm_id=e826b8c50a0a3c1e019410bb1031d102' + '&sysparm_category=hardware' + '&sysparm_comments=Hello World!!!';
```
--------------------------------
### Execute CompanyOne API Integration
Source: https://servicenowguru.com/scripting/implementing-a-factory-pattern-on-servicenow
This is an example of how to initiate the integration logic for CompanyOne. Ensure the CompanyOneAPI script include is correctly defined.
```javascript
new CompanyOneAPI().execute()
```
--------------------------------
### Using GlideSchedule (Calgary+)
Source: https://servicenowguru.com/system-definition/weekdaysonly-scheduled-job
This example demonstrates how to use GlideSchedule, which replaces the older 'Packages.com.glide.schedules' calls, starting from the Calgary release. It checks if the current date and time falls within a specified schedule.
```javascript
var gr = new GlideRecord('cmn_schedule');
if (gr.get('name', 'Weekdays 08:00 - 17:00')) {
var schedule = new GlideSchedule(gr.sys_id);
if (schedule.isInSchedule(new GlideDateTime())) {
u_sendApprovalReminders();
}
} else {
gs.log('*** Approval Reminder - Schedule not found');
}
```
--------------------------------
### Get Related Records - Parent CIs
Source: https://servicenowguru.com/scripting/script-includes-scripting/walking-servicenowcom-cmdb-relationship-tree
Retrieves related records for a given CI, specifically focusing on parent relationships. This example demonstrates how to fetch an ArrayList of related CIs based on a 'child' relationship type.
```javascript
var al = g.getRelatedRecords(value, null, ‘cmdb_ci’, ‘cmdb_ci’, ‘child’); // returns ArrayList
```
--------------------------------
### Construct Catalog Item URL with Parameters
Source: https://servicenowguru.com/client-scripts-scripting/parse-url-parameters-client-script
Example of building a URL for a Service Catalog item, including parameters for item ID, category, and comments. These parameters can be parsed by an 'onLoad' client script.
```javascript
var url = 'com.glideapp.servicecatalog_cat_item_view.do?sysparm_id=e826b8c50a0a3c1e019410bb1031d102' + '&sysparm_category=hardware' + '&sysparm_comments=Hello World!!!';
```
--------------------------------
### Get Reference Data and Update Form Fields
Source: https://servicenowguru.com/client-scripts-scripting/gform-getreference-callback
Use gform.getReference with a callback to fetch data from a reference field and update other fields. This example retrieves caller information and sets the location, also applying VIP styling if applicable.
```javascript
function onChange(control, oldValue, newValue, isLoading) {
//Get the 'caller_id' field and label elements
var callerLabel = $('label.incident.caller_id');
var callerField = $('sys_display.incident.caller_id');
//Get the 'location' field
var loc = g_form.getElement('location');
//If the 'caller_id' field contains a valid reference
if(newValue){
//Get the caller object so we can access fields
//Calls the 'popCallerInfo' function when the value is returned
var caller = g_form.getReference('caller_id', popCallerInfo);
}
//If the 'caller_id' field does not contain a valid reference
else{
//Clear the value of the 'location' field
if(loc){
g_form.setValue('location', '');
}
//Remove any VIP styles present
callerLabel.setStyle({backgroundImage: ""});
callerField.setStyle({color: ""});
}
//Nested 'getReference' callback function for variable access
function popCallerInfo(caller){
//Location setting section
if(loc && !isLoading && newValue != oldValue){
g_form.setValue('location', caller.location);
}
//VIP formatting section
if(caller.vip == 'true'){
//Change the 'caller_id' label to red background with VIP icon
var bgPosition = "95% 55%";
if (document.documentElement.getAttribute('data-doctype') == 'true')
bgPosition = "5% 45%";
callerLabel.setStyle({backgroundImage: "url(images/icons/vip.gif)", backgroundRepeat: "no-repeat", backgroundPosition: bgPosition});
//Change the 'caller_id' name field to red text
callerField.setStyle({color: "red"});
}
else{
//Not a VIP, remove temporary styles
callerLabel.setStyle({backgroundImage: ""});
callerField.setStyle({color: ""});
}
}
}
```
--------------------------------
### Get Related Records using GlideRecord
Source: https://servicenowguru.com/cmdb/walking-servicenowcom-cmdb-relationship-tree
This example demonstrates how to use the gc.getRelatedRecords method to retrieve related records from a CMDB CI table. Note that this method may not be supported in older ServiceNow versions like Eureka, potentially causing IndexOutOfBoundsException errors.
```javascript
var list = gc.getRelatedRecords(ciSysId, null, "cmdb_ci", "cmdb_ci", relation); // returns ArrayList
for(var idx = 0; idx < list.size(); idx++) {
```
--------------------------------
### Initialize CIUtils2 Script Include
Source: https://servicenowguru.com/scripting/script-includes-scripting/walking-servicenowcom-cmdb-relationship-tree
Initializes the CIUtils2 Script Include with default properties for maximum depth, CI object, size threshold, and tracking variables.
```javascript
gs.include("PrototypeServer");
var _CIUtils_2 = Class.create();
_CIUtils_2.prototype = {
initialize : function() {
this.maxDepth = gs.getProperty('glide.relationship.max_depth',10); // how deep to look
this.currentDepth = 0;
this.CIs = {}; // list of affected CIs
this.maxSize = gs.getProperty('glide.relationship.threshold',1000); // how many records to return
this.added = 0; // track how many added, since can't get size() for an Object
this.parents = {}; // track parents already iterated
},
/** Following Script has been made based on
* CIUtils2
* https://servicenowguru.com/scripting/script-includes-scripting/walking-servicenowcom-cmdb-relationship-tree/
* I've added some new funtions (such as just getting all CI's from a certain Class, Assigned To, Department, Location)
*/
/*----*/
/**
* Determine which CIs are affected by a specific CI
*
* Inputs:
* id is the sys_id of a configuration item (cmdb_ci)
* classArr is an array of CI class names that should be returned
*
* Returns:
* an array of sys_id values for cmdb_ci records downstream of
* (or affected by) the input item
*/
cisAffectedByCI: function(id, classArr) {
var ci = new GlideRecord('cmdb_ci');
ci.get(id);
//If no class specified then assume business service
if(classArr == null){
classArr = ['cmdb_ci_service','service_offering'];
for (var ciClass in classArr){
if (ci.sys_class_name == classArr[ciClass]){
this._addCI(id, this.CIs);
}
}
}
//If class = 'ALL' then just add the CI
else if(classArr[0] == 'ALL'){
this._addCI(id, this.CIs);
}
else{
for (var ciClass2 in classArr){
if (ci.sys_class_name == classArr[ciClass2]){
this._addCI(id, this.CIs);
}
}
}
this._addParentCIs(id, this.CIs, this.currentDepth, classArr);
var ciarr = []; // CIs is an Object, convert to Array for final query
for (var i in this.CIs)
ciarr.push(i);
return ciarr; // list of affected CIs
},
/*----*/
/**
* Determine which CIs are affected by a task
*
* Inputs:
* task is a task GlideRecord (e.g., incident, change_request, problem)
* classArr is an array of CI class names that should be returned
*
* Returns:
* an array of sys_id values for cmdb_ci records downstream of
* (or affected by) the configuration item referenced by the task's cmdb_ci field and Affected CIs list
*/
cisAffectedByTask: function(task, classArr) {
//Find the impacted CIs for the 'cmdb_ci' value
var id = task.cmdb_ci.toString();
var allCIArr = [];
if(id){
allCIArr = this.cisAffectedByCI(id, classArr);
}
```
--------------------------------
### Prompt Box for User Input
Source: https://servicenowguru.com/client-scripts-scripting/javascript-popup-boxes-servicenow
Utilize a prompt box in a client-side UI action to get user input before proceeding. The box returns the input value if 'OK' is clicked, or null if 'Cancel' is clicked. This example sets a comment and submits the record if the user types 'Continue'.
```javascript
function promptUser(){
var con = prompt("This is really dangerous. \nType 'Continue' if you really want to perform this action.");
if(con == 'Continue'){
g_form.setValue('comments', 'Dangerous action performed.');
gsftSubmit(gel('sysverb_update_and_stay'));
//gsftSubmit(gel('sysverb_update'));
}
else{
return false;
}
}
```
--------------------------------
### Create a 'Factory' Script Include
Source: https://servicenowguru.com/scripting/implementing-a-factory-pattern-on-servicenow
Define a placeholder script include to act as a factory for creating other objects. This script include does not require complex logic but serves as a record for dynamic object creation.
```javascript
var Factory = Class.create();
Factory.prototype = {
/*
This script include is used purely as a placeholder to build other objects for instantiation. It is referenced in other script includes and the script attribute is 'written' too but never saved. That
script is then executed to dynamically give the object that is needed based on the attributes passed in the the "factory".
*/
initialize: function() {},
type: 'Factory'
};
```
--------------------------------
### Transform Script Example
Source: https://servicenowguru.com/integration/using-import-sets-rest-integration
An example of a server-side JavaScript for data manipulation within a Transform Map.
```APIDOC
### Transform Script Example
This script demonstrates how to set a default value for a field if it is empty during the transformation process.
**Type:** onBefore (or other applicable script type)
**Code:**
```javascript
(function transformRow(source, target, map, log, isUpdate) {
// Example: Set a default value if a field is empty
if (!source.field_name) {
target.field_name = 'Default Value';
}
})(source, target, map, log, isUpdate);
```
```
--------------------------------
### SAML Response XML Example
Source: https://servicenowguru.com/single-sign-on/demystifying-saml
This is an example of a SAML Response XML. It contains assertion details, status, and attribute information.
```xml
http://www.okta.com/exkhbgik0lUIiSbJO5d7
http://www.okta.com/exkhbgik0lUIiSbJO5d7
harry.potter@gmail.com
https://dev216916.service-now.com
urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport
Harry
Potter
harry.potter@gmail.com
```
--------------------------------
### CIUtils2 Initialize Method
Source: https://servicenowguru.com/scripting/script-includes-scripting/walking-servicenowcom-cmdb-relationship-tree
Initializes the CIUtils2 class with properties like maxDepth, currentDepth, CIs, maxSize, added count, and parents tracking.
```javascript
var _CIUtils_2 = Class.create();
_CIUtils_2.prototype = {
initialize : function() {
this.maxDepth = gs.getProperty('glide.relationship.max_depth',10); // how deep to look
this.currentDepth = 0;
this.CIs = {}; // list of affected CIs
this.maxSize = gs.getProperty('glide.relationship.threshold',1000); // how many records to return
this.added = 0; // track how many added, since can't get size() for an Object
this.parents = {}; // track parents already iterated
},
/** Following Script has been made based on
* CIUtils2
* https://servicenowguru.com/scripting/script-includes-scripting/walking-servicenowcom-cmdb-relationship-tree/
* I've added some new funtions (such as just getting all CI's from a certain Class, Assigned To, Department, Location)
*/
/*----*/
/**
* Determine which CIs are affected by a specific CI
*
* Inputs:
* id is the sys_id of a configuration item (cmdb_ci)
* classArr is an array of CI class names that should be returned
*
* Returns:
* an array of sys_id values for cmdb_ci records downstream of
* (or affected by) the input item
*/
```
--------------------------------
### Enhanced Business Rule for Order Guide Population
Source: https://servicenowguru.com/system-definition/populate-order-guide-request-ticket
This advanced business rule script enhances the reliability of populating the 'Order guide' field. It includes checks to ensure at least one item from the order guide's rule base is present in the order and verifies that any rule base entry with no condition is included. This helps mitigate errors caused by users clicking on order guide items as standalone services.
```javascript
var c = new GlideRecord('sc_cart');
c.get('user', gs.getUserID());
// Check if the cart has an order guide associated
if (c.current_guide) {
var orderGuideSysId = c.current_guide;
var orderGuideGR = new GlideRecord('sc_order_guide');
if (orderGuideGR.get(orderGuideSysId)) {
var ruleBaseGR = new GlideRecord('sc_order_guide_rule_base');
ruleBaseGR.addQuery('order_guide', orderGuideSysId);
ruleBaseGR.query();
var hasRequiredItem = false;
var hasUnconditionalItem = false;
// Check if any item from the order guide is in the current request
var requestedItemsGR = new GlideRecord('sc_req_item');
requestedItemsGR.addQuery('request', current.sys_id);
requestedItemsGR.query();
var includedItemSysIds = [];
while(requestedItemsGR.next()) {
includedItemSysIds.push(requestedItemsGR.cat_item.toString());
}
while (ruleBaseGR.next()) {
// Check if any item from the rule base is included in the request
if (includedItemSysIds.indexOf(ruleBaseGR.catalog_item.toString()) > -1) {
hasRequiredItem = true;
}
// Check for unconditional items
if (!ruleBaseGR.condition) {
hasUnconditionalItem = true;
// If an unconditional item is present, it must be included
if (includedItemSysIds.indexOf(ruleBaseGR.catalog_item.toString()) === -1) {
hasRequiredItem = false; // Override if unconditional item is missing
}
}
}
// Only populate if a required item or an unconditional item is present
if (hasRequiredItem || hasUnconditionalItem) {
current.u_order_guide = orderGuideSysId;
}
}
}
```
--------------------------------
### GlideRecord 'Get' Query by Sys ID
Source: https://servicenowguru.com/scripting/gliderecord-query-cheat-sheet
Use the 'get' method to retrieve a single record when you know its sys_id. This can be used on both server-side and client-side.
```javascript
var gr = new GlideRecord('incident');
gr.get(sys_id_of_record_here);
//Do something with the record returned
if(gr.category == 'software'){
gs.log('Category is ' + gr.category);
}
```
--------------------------------
### Auto-Select Prerequisite Software (onChange Client Script)
Source: https://servicenowguru.com/client-scripts-scripting/checkbox-variables-mandatory
This client script automatically selects a prerequisite software ('var_X') if another software ('var_Y') is selected. It also handles making 'var_X' read-only while 'var_Y' is selected and reverts the state when 'var_Y' is deselected. This script is intended for catalog items.
```javascript
function onChange(control, oldValue, newValue, isLoading) {
if (newValue == 'false') {
g_form.setValue("var_X", 'false');
g_form.setReadOnly('var_X',false);
return;
}
if (g_form.getValue("var_Y", 'true')) {
g_form.setValue("var_X", 'true');
```
--------------------------------
### GlideRecord Query Example
Source: https://servicenowguru.com/system-ui/ui-actions-system-ui/copy-ui-action-change-requests-part-2
This snippet demonstrates how to query the 'task_ci' table. It's useful for checking existing entries related to a task.
```javascript
var taskCiGr = new GlideRecord('task_ci');
taskCiGr.addQuery('task', current.sys_id);
taskCiGr.query();
if (taskCiGr.next()) {
// CI found
}
```
--------------------------------
### Client Script for KB Search Pop-up (Record Producer)
Source: https://servicenowguru.com/client-scripts-scripting/mandatory-knowledge-search-ticket-creation
This client script is designed for record producers and also uses an 'onLoad' trigger to display knowledge base search results in a pop-up. Ensure the 'short_description' variable is correctly configured.
```javascript
function onLoad() {
//Call to display the KB search
var kbSearch = new GlideRecord('kb_knowledge');
kbSearch.addQuery('short_description', producer.short_description);
kbSearch.query();
var kbUrl = "kb_find.do?sysparm_query=" + kbSearch.getEncodedQuery();
kbUrl += "&sysparm_first_row="+kbSearch.getOffset();
kbUrl += "&sysparm_view=mobile";
kbUrl += "&sysparm_list_url="+current.getTableName()+".do?sys_id="+current.sys_id;
kbUrl += "&sysparm_list_field=short_description";
kbUrl += "&sysparm_list_table="+current.getTableName();
//Open the KB search in a popup window
popupOpen(kbUrl, 'Knowledge Base Search', 800, 600, '');
}
```
--------------------------------
### SAML Request XML Example
Source: https://servicenowguru.com/single-sign-on/demystifying-saml
This is an example of a SAML Request XML captured by the SAML DevTools extension. It includes details like AssertionConsumerServiceURL, Destination, and NameIDPolicy.
```xml
https://dev216916.service-now.com
urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport
```
```xml
https://dev216916.service-now.com urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport
```
--------------------------------
### Basic Dynamic Filter Examples
Source: https://servicenowguru.com/reporting/harnessing-power-dynamic-filters-servicenow
These are examples of dynamic filter query strings that can be directly pasted into filter criteria. They are typically used for simple, predefined queries.
```javascript
javascript:gs.getUserID();
```
```javascript
javascript:getRoledUsers();
```
--------------------------------
### Initialize ChecklistCreator
Source: https://servicenowguru.com/scripting/servicenow-checklist-automation-simplifying-catalog-task-management
Initializes the ChecklistCreator Script Include. No specific setup is required for this method.
```javascript
initialize: function() {}
```
--------------------------------
### Get Record Count Server-Side with getRowCount
Source: https://servicenowguru.com/scripting/gliderecord-query-cheat-sheet
Retrieve the total number of records returned by a server-side GlideRecord query. This is an efficient way to get the count after a query.
```javascript
var gr = new GlideRecord('incident');
gr.addQuery('category', 'software');
gr.query();
gs.log('Incident count: ' + gr.getRowCount());
```
--------------------------------
### OnBefore Transform Script for Hardware Asset Imports
Source: https://servicenowguru.com/imports/simplifying-data-imports-parties
This script runs before transforming source data into the Hardware (alm_hardware) table. It validates inventory category, checks for missing manufacturer part numbers and serial numbers, and uses the Vendor Translation table (u_vendor_translation) to map vendor models to ServiceNow models. Error conditions are logged.
```javascript
(function runTransformScript(source, map, log, target /*undefined onStart*/ ) {
var errorCondition = false;
var itemModel = '';
var modelDisp = '';
var vendorName = 'Name of the vendor company';
//Set the sourceRow variable to allow for input into the log statements the row from the source that failed
var sourceRow = source.sys_import_row + 2;
var excPrefix = 'Exception: Asset Import HW ASN ' + vendorName + ': Source Data Row ' + sourceRow + ': ';
// Do not transform the source record unless the source u_inventory_category field contains the text string "computer.system". This filters out non-computer hardware that may be included in the ASN. Log an Error if the inventory category value does not contain ".Computer Systems.".
if (source.u_inventory_category.indexOf('.COMPUTER SYSTEMS.') == -1){
//log.error(excPrefix + 'Item not a hardware asset (inventory category field does not contain ".computer system.")');
errorCondition = true;
}
else{
// Check for empty vendor model number in source, Log ERROR with message per error exception
if(JSUtil.nil(source.u_mfg_part_num) == true){
log.error(excPrefix + 'Manufacturer part number (mfg part num) missing in source data');
errorCondition = true;
}
else{
// Perform lookup against custom translation table, using vendor and vendor model key as the unique identifiers
//query the table for model translations for the selected vendor
var gr2 = new GlideRecord('u_vendor_translation');
gr2.addQuery('u_vendor', 'SysID of the vendor\'s record in the core_company table');
gr2.addQuery('u_vendor_model', source.u_mfg_part_num);
gr2.addActiveQuery();
gr2.query();
// Confirm if match found, if not, raise ERROR exception into import log
if(gr2.next()){
//Set the MODEL FIELD on the record so we don't need to query the table again in a field map script
source.model = gr2.u_sn_model.sys_id;
target.model = gr2.u_sn_model;
//set the itemModel field for use in another query later
itemModel = gr2.u_sn_model;
modelDisp = gr2.u_sn_model.getDisplayValue();
target.model_category = gr2.u_sn_model.cmdb_model_category;
}
else{
log.error(excPrefix + 'Source model ' + source.u_mfg_part_num + ' does not match a model in Service-Now. Check vendor translation table to ensure a translation is set up.');
errorCondition = true;
}
}
// Check for empty serial number, if empty, Log ERROR with message per error exception logging section below
if (JSUtil.nil(source.u_serial_num) == true){
log.error(excPrefix + 'Serial number missing in source data');
errorCondition = true;
}
else{
// Confirm that the serial number does not exist in the alm_asset table already as that same model, if so, raise ERROR exception
var modelDesc = '';
var gr1 = new GlideRecord('alm_asset');
gr1.addQuery('serial_number', source.u_serial_num);
//If we found a model through the translation table record, perform an additional filter on the model to make sure we don't have a duplicate model + serial number combo
if (itemModel != ''){
gr1.addQuery('model', itemModel);
//set the modelDesc variable to include that optionally in an error code if applicable
modelDesc = 'with model number ' + modelDisp + ' ';
}
gr1.query();
if(gr1.next()){
```
--------------------------------
### GlidePaneForm with Parameters
Source: https://servicenowguru.com/scripting/client-scripts-scripting/parse-url-parameters-client-script
Demonstrates how to use GlidePaneForm to open a new record and pass parameters. Note that alert(window.location.href) might not show parameters in this context.
```javascript
var dialog = new GlidePaneForm(‘new_item’, ‘incident’);
dialog.setTitle(“New Incident”);
dialog.setSysID(-1);
dialog.addParm(‘sysparm_view’, ‘Add’);
dialog.addParm(‘sysparm_tid’, ‘Test TID’);
dialog.addParm(‘sysparm_form_only’, ‘true’);
dialog.render();
```
--------------------------------
### Getting Old Values with GlideRecordScriptUtil
Source: https://servicenowguru.com/client-scripts-scripting/checking-modified-fields-script
In a business rule, you can get changed field names using gru.getChangedFieldNames() and then retrieve the old value using previous.getValue() with the field name.
```javascript
gru.getChangedFieldNames()
```
```javascript
previous.getValue()
```