top of page
Writer's picturesajan Allan Roy R

Some Useful ServiceNow scripts

Updated: Jun 13, 2021

Set/generate a sys_id for a new record:

setNewGuid() //generates a new sys_id for a new record
setNewGuidValue("sys_id") //creates record with sys_id. same in scoped too 

Show embedded lists:

var vlist = $$('div[tab_caption="Affected CIs"]'[0];
if(list.hasClassName('embedded')){
list.show();
}

g_form:

g_form.flash("comments","#FFFACD",0); //
g_form.addDecoration("field","icon","title");//sets an icon on field label
g_form.getActionName(); //returns the recent UI action clicked

g_form.getRelatedListNames(); //returns as an array in the order they are present on the form

g_form.getSectionNames(); //shows all sections, even if not visible
g_form.getSections(); //shows all sections on the form
g_form.getUniqueValue(); //returns sys_id of the record
g_form.hideRelatedLists(); //hides all RLs on the form

g_form.isLiveUpdating(); //returns boolean whether a field was updated live while on the form

g_form.isSectionVisible(); //returns true if section is visible

g_form.onUserChangeValue(); //event listener to check if user changes value

/*var handler = function(fieldname, originalValue, newValue) {   console.log('The field ('+ fieldname + ') has a new value of: ' + newValue); // function code 
}

var unregister = g_form.onUserChangeValue(handler);   // To unregister the event listener unregister();
*/

g_form.refreshSlushBucket('field'); //refreshes a slushbucket
g_form.save(); //saves a record without redirecting

g_user:

g_user.userID; //returns sys_id of user
g_user.hasRoleFromList("comma-seperated list") //checks if user has roles
g_user.hasRoleExactly("itil"); //checks if user has only this role

Date operations on client-side:

var date_number = getDateFromFormat(g_form.getValue('the_date_field'), g_user_date_format); //can use g_user_date_time_format for time component
var my_date = new Date(date_number);

newDate().getTime(); //gets a new date/time value on client-side

spUtil:

spUtil.createUid(); //generates a new sys_id

spUtil.format('An error ocurred: {error} when loading {widget}', {error: '404', widget: 'sp-widget'}) //formats the string better

spUtil.getURL(); //gets current portal url
spUtil.isMobile(); //checks if the UI is mobile

spUtil.recordWatch($scope, "table", "filter", function(response){
//use response.data here
}); //watches over live updates on the specified records from table+filter

spUtil.setBreadCrumb(); //update the header breadcrumbs

GlideList:

g_list.addfilter("active=true"); //adds a single-term filter

var list = GlideList2.get("list_id"); //gets the list
list.getChecked(); //returns sys_ids of records that are checked
//contd
list.getListName(); //gets the name of the list (table)
list.getQUery(); //gets encoded query of the list filter
list.getView(); //returns name of the list view
list.isUserList(); //returns boolean if user personalised the list
list.refresh(); //refreshes the list
list.setFilterAndRefresh(); //sets filter and refreshes the list
list.setRowsPerPage(); //sets rows per page, might have to refresh
list.sort(); //sorts the list based on the field mentioned

 

ArrayUtil:

new arrayUtil().concat(a1, a2); //concatenates array a1 & a2
new ArrayUtil().contains(a1, "x"); //searches array a1 if 'x' is present
new ArrayUtil().intersect(a1, a2); //find common elements in arrays
new ArrayUtil().unique(a1); //removes duplicates from an array

GlideImpersonate:

impersonateUser: function(userId) {   
var impUser = new GlideImpersonate();   
impUser.impersonate(userId);  
}
//contd
impUser.isImpersonating(); //finds if the current user is impersonating
impUser.canImpersonate(); //checks if a user can impersonate

GlideRecord:

//finds all matching records of aller_id on incident table that match with the opened_by on problem table
var now_GR = new GlideRecord('problem'); 
now_GR.addJoinQuery('incident', 'opened_by', 'caller_id');  now_GR.query();

gr.applyTemplate(); //applies template to a new gr record initialized

gr.getFields(); //returns a java array of fields and their values
//Example:
var fields = gr.getFields();
for (var i = 0; i < fields.size(); i++) {   
var glideElement = fields.get(i);   
if (glideElement.hasValue() && glideElement.getName() == 'number') {     gs.print('  ' + glideElement.getName() + '\t' + glideElement);   
    } 
}

gr.getLink(); //gets the url link of the glideRecord
gr.setQueryReferences(); //returns display names of ref fields if true

GlideScopedEvaluator:

//evaluate script from script field 'run_script'on the gr record
//optionally pass variables to the stored script:
//var vars = {'greeting' : 'hello'};

var evaluator = new GlideScopedEvaluator(); gs.info(evaluator.evaluateScript(gr, 'run_script', vars));  

evaluator.evaluateScript(gr, 'run_script', null); gs.info(evaluator.getVariable('result')); //get result

Get a reference record without glide:

var grAG = current.assignment_group.getRefRecord();

//get glideRecord fields (if needed, as objects) using a gr record
var obj = getGrObject(grIncident, ["sys_id", "caller_id", "description"]);
var jsonObj = JSON.stringify(obj);

g_service_catalog:

//helps access variables on the MRVS modal
function onLoad() {   
if (g_service_catalog.parent.getValue("field") == "value") {     g_form.setValue("mrvs_field1", "mrvs_fieldvalue");     g_form.setVisible("mrvs_field2", "false");   } }

mrvs operations:

var mrvs = current.variables.mrvs_name; //gets the mrvs as a json
mrvs.getRowCount(); //returns the row count
var row = mrvs.getRow(i); //when in a for-loop, iterates through the row i
row.var_name; //returns the variable value in the mrvs

row.var_name = 'value'; //sets the value to the variable
current.variables.mrvs_name = JSON.stringify(modified_mrvs_var);
//both the above lines should be executed to update a mrvs variable

Get journal entry without the header:

var journalFieldName = 'comments';
var journalText = current[journalFieldName]
    .getJournalEntry(1)
    .trim()
    .split('\n')
    .slice(1)
    .join('<br />\n');

GlideExcelParser:

Full documentation here .

var parser = new sn_impex.GlideExcelParser();  
var attachment = new GlideSysAttachment(); // use attachment sys id of an excel file
var attachmentStream = attachment.getContentStream(<attachmentsysid>);  parser.parse(attachmentStream);   //retrieve the column headers 
var headers = parser.getColumnHeaders();   
var header1 = headers[0];  
var header2 = headers[1];

Schedule job trigger:

var rec = new GlideRecord('sysauto_script');
rec.get('name', 'scheduled_script_name');
SncTriggerSynchronizer.executeNow(rec);




960 views0 comments

Recent Posts

See All

GlideQuery() Demystified

I have been hearing a lot about GlideQuery() lately, so after spending some time learning what it is about, I am sharing the below...

Комментарии


bottom of page