Skip to content

raphaelcrv/servicenow-snippets

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ServiceNow & JS Snippets

Table of Contents

Working in progress

Oficial Library Documentations

Examples:


Oficial Documentation Reference

  1. Woring with GlideRecord
  2. Glide User
  3. Working with GlideDateTime
  4. JavaScript Snippets
  5. Array Utils
  6. HTML Snippets
  7. SASS Variables
  8. CSS
  9. Misc
  10. Components
  11. Widget Generate Catalog
  12. Widget Generate Catalog

  1. GlideForm: The GlideForm API provides methods to customize forms.
  2. GlideModalV3: Provides methods for displaying a content overlay.
  3. GlideUser:The GlideUser API provides access to information about the current user and current user roles.
  4. Jelly Sample Code

Using gs.nil()

if(gs.nil(gr.variableName)) {
  /*true condition*/
  }

if(valueData != '' && valueData != null && !valueData.nil(){
  /*true condition*/
  }

gs.nil() will return true if a variable is empty

GlideRecord

GlideRecord.get

//Using the new 
//initialize(): Creates an empty record suitable for population before an insert.
//newRecord(); Creates a GlideRecord, set the default values for the fields and assign a unique id to the record.

//initialize gives no value to opened_at
var inc = new GlideRecord('incident');
inc.initialize();
gs.print(inc.opened_at.getDisplayValue());
inc.name = 'New Incident';
inc.description = 'Incident description';
inc.insert();

//newREcord() gives value to opened_at
var inc = new GlideRecord('incident');
inc.newRecord();
gs.print(inc.opened_at.getDisplayValue());
inc.name = 'New Incident';
inc.description = 'Incident description';
inc.insert();


//Example get encoded query
var queryString = "priority=1^ORpriority=2"; //query
var gr = new GlideRecord('incident');
slagr.setLimit("1"); //setLimit
slagr.orderByDesc('u_ticket_score'); //orderBy
gr.addEncodedQuery(queryString);//EncodedQuery
gr.query();
while (gr.next()) {
  //This method fails if there is a field in the table called "next". If that is the case, use the method _next().
gs.addInfoMessage(gr.number);
gs.info(gr.getValue('number')); //Retrieves the string value of an underlying element in a field.
}

//exemple get sys_id
var sys_id = "99ebb4156fa831005be8883e6b3ee4b9";
var gr = new GlideRecord('incident');
if(gr.get(sys_id)){
gs.info(gr.number) // logs Incident Number
}

//exemple get param
var gr = new GlideRecord('incident');
if(gr.get('caller_id.name','Sylivia Wayland')){
gs.info(gr.number) // logs Incident Number
}

//example if ternary get function
function getRecord (sys_id, table) {
var gr = new GlideRecord(table);
return gr.get(sys_id); //return true or false
}

gr.get return true if record founded or the value of record if founded

Keywords: GlideRecord, get


GlideRecord.update

//update one record
var gr = new GlideRecord('incident');
gr.addQuery('emailLIKE@domain');
gr.addEncodedQuery(queryString);//EncodedQuery
gr.setLimit(1);
gr.query();
while (gr.next()) {
  grInc.state = 2;
  gr.update();
}

//update updateMultiple
var gr = new GlideRecord('incident');
gr.addEncodedQuery("state=2");//EncodedQuery
gr.query();
while (gr.next()) {
  //grInc.setValue("state",2)//set value
  grInc.state = 2;
  gr.updateMultiple();
}

//exemple get sys_id
var sys_id = "99ebb4156fa831005be8883e6b3ee4b9";
var grInc = new GlideRecord('incident');
if(grInc.get(sys_id)){
  //grInc.setValue("state",2)//set value
  grInc.state = 2;
  grInc.update()
}

/updateMultiple() records
// update the state of all active incidents to 4 - "Awaiting User Info"
var gr = new GlideRecord('incident');
gr.addQuery('active', true);
gr.setValue('state',  4);
gr.updateMultiple();

Notes on the snippet Resume: that code update password of all users on the filter Caution: User gr.setWorkflow = false for skipp workflow rules tags: GlideREcord, Update


Examples gr.delete()

//Deletes multiple records according to the current "where" clause.
function nukeCart() {
var cart = getCart();
var id = cart.sys_id;
var kids = new GlideRecord('sc_cart_item');
kids.addQuery('cart', cart.sys_id);
kids.deleteMultiple();
}


//Delete single record
var gr = new GlideRecord('incident');
if (gr.get('99ebb4156fa831005be8883e6b3ee4b9'))
    gr.deleteRecord();

/

___________________________________

## Examples  `addJoinQuery` :
```js
//Find problems that have incidents associated where the incident caller_id field value matches that of the problem opened_by field.
var gr = new GlideRecord('problem'); 
gr.addJoinQuery('incident', 'opened_by', 'caller_id'); 
gr.query();,
while (gr.next()) {
  gs.info(gr.getValue('number'));
}

Keywords: addJoinQuery, get


Examples gr.getLastErrorMessage()

// Setup a data policy where short_description field in incident is mandatory
var gr = new GlideRecord('incident');
gr.insert(); // insert without data in mandatory field
var errormessage = gr.getLastErrorMessage(); 
gs.info(errormessage);

Output: Data Policy Exception: Short description is mandatory


Examples getLink(Boolean noStack)

gr = new GlideRecord('incident');
gr.addActiveQuery();
gr.addQuery("priority", 1);
gr.query();
gr.next()
gs.info(gs.getProperty('glide.servlet.uri') + gr.getLink(false));

Output: /incident.do?sys_id=9d385017c611228701d22104cc95c371&sysparm_stack=incident_list.do?sysparm_query=active=true

Snippets Server

Transform Map Demo Script

  1. input value userID with blank spaces and missing char to fill with zero '123, 123, 21';
  2. output convert to string splited by comma with UserSysID 'sysid1,sysid2,sysid3'
// 
//convert to string-> suing split to transform in array
var s_ponto_focal = ((source.u_ponto_focal).toString()).split(",");
var b_ponto_focal = '';
var a_ponto_focal = '';
var maxChar = 9;

for (var i = 0; i < s_ponto_focal.length; i++) {

//remove blank spaces
s_ponto_focal[i] = s_ponto_focal[i].replace(' ','');

//get the missing zeros
  qtdChar = parseInt(maxChar) - parseInt((s_ponto_focal[i]).length);
  if (qtdChar > 0) {
    var z = 0;
    var zero = '';
  
    for (z = 0; z < qtdChar; z++) {
      zero += '0';
    }
//concat the missing zeros
    s_ponto_focal[i] = zero + s_ponto_focal[i];
  }
  
//query find sys_id -> concat to a_ponto_focal split by comma
  var user_table = new GlideRecord('sys_user');
  user_table.addQuery('active', 'true');
  user_table.addQuery('user_name', s_ponto_focal[i]);
  user_table.query();
  if (user_table.next()) {
    if (a_ponto_focal.length > 1) {
      a_ponto_focal += ',' + user_table.sys_id;
    }else{
      a_ponto_focal += user_table.sys_id;
    }

  }
}

//set target values 
target.vendor_manager = a_ponto_focal;
target.vendor = true;
target.vendor_type = "OutSourcing";

Notes on the snippet


Debug ScriptInclude Example:

var MyUtil = Class.create();

MyUtil.prototype = {
  initialize: function(){
      this.debug       = gs.getProperty('debug.MyUtil') == 'true';
      this.debugPrefix = '>>>DEBUG: MyUtil: ';
  },

  myMethod : function(id) {

      // Some logic here
      this._debug('myMethod(): Sample debug output');
  },

  _debug : function(msg) {

      if (this.debug) {
          gs.debug(debugPrefix + msg);
      }
  },

  type : "MyUtil"
}

Keywords: script include, sys_log, debug


Filtering choices lists (Use reference qualifier)

alt text

javascript:"u_contractISNOTEMPTY^u_contract =" + current.variables.contract

current.variables.contract => get value the variable on the form
u_contractISNOTEMPTY^ => condition u_contract nĂŁo deve estar vazio

Keywords: Use_reference_qualifier, filter_choice_list


Examples etch a record with all fields from query object

fetch a record with all fields from query object at a time while retrieving the data from GlideRecord

var grData = [];
var gr = new GlideRecord('incident');
gr.addEncodedQuery('state=2');
gr.query();
while (gr.next()) {
  var packageToSend = {}
  for (var property in gr) {
    try {
      packageToSend[property] = gr[property].getDisplayValue();
    }
    catch(err){}
  }
  grData.push(packageToSend)
}

grData.forEach(function(e,i){  
  //all fields from incident table are avaibale 
  gs.log(e.number);
  
});

Keywords: GlideRecord, get

Working with Dates

Get Days Ago

_checkDaysAgo: function (date) {
  //take date to find today, yesterday, etc.
  var now = gs.now() + ' 12:00:00';
  date = date.substring(0, 10) + ' 12:00:00';

  var nowDT = new GlideDateTime();
  nowDT.setDisplayValue(now);
  var dateDT = new GlideDateTime();
  dateDT.setDisplayValue(date);
  var seconds = gs.dateDiff(dateDT.getDisplayValue(), nowDT.getDisplayValue(), true);

  var days = seconds / 60 / 60 / 24;

  return days;
}

Notes on the snippet


Working with dates - GlideDateTime:

Comparing if a Date is Less Than Current Date

var date = new GlideDateTime(date_field);
var now = new GlideDateTime();
if(date <= now) {
  // date is in the past
}


var mClass = {
formatData : function(data){
  var dia  = data.split("/")[0];
  var mes  = data.split("/")[1];
  var ano  = data.split("/")[2];

  return ano + '-' + ("0"+mes).slice(-2) + '-' + ("0"+dia).slice(-2);
  // Utilizo o .slice(-2) para garantir o formato com 2 digitos.
}

}

var gdt1 = new GlideDateTime(this.mClass.formatData("01/04/2020"));
var gdt2 = new GlideDateTime();

gs.log("GDT1 -> " + gdt1.getValue());
gs.log("GDT2 -> " + gdt2.getValue());

gs.log("GDT1("+gdt1.getValue()+") antes de GDT2 ("+ gdt2 +")?");

gs.info(gdt1.before(gdt2));  


Example 2




//604800000 


var today = new GlideDateTime();

var gr = new GlideRecord('u_eficiencia');
gr.addQuery('u_number=EFI0001193');
gr.setLimit(1);
gr.query();
while (gr.next()) {
gr.setWorkflow(false);

if(gr.getValue('u_last_update')){

}else{

  var sevenDays = new GlideDateTime(gr.getValue('sys_created_on'));
  sevenDays.add(604800000); //add 7days

  if(today.after(sevenDays)){
    gr.setValue('u_pontos_eficiencia',parseInt(gr.getValue('u_pontos_eficiencia')) + 1);
    
    gs.print(today.toString());
    gr.setValue('u_last_update',today.toString())
  }
    
}
gr.update();
}

Notes on the snippet


Scrapping content from internet

var el = $(".xuxa tr")
arrDDD = []
for (var i = 0; i < el.length; i++){
  
  arrDDD.push({
  ddd : $(el[i]).children('td:eq(1)').html(),
  state : $(el[i]).children('td:eq(0)').html(),
  })
};

Notes on the snippet

if(gs.nil(gr.variableName)) { //is empety }
inc.autoSysFields(false);  // Do not update sys_updated_by, sys_updated_on, sys_mod_count, sys_created_by, and sys_created_on
inc.setWorkflow(false);    // Do not run any other business rules

current.setAbortAction(true); //Sets a flag to indicate if the next database action (insert, update, delete) is to be aborted. ref:[https://developer.servicenow.com/dev.do#!/reference/api/orlando/server_legacy/r_GlideRecord-setAbortAction_Boolean]
gr.setLimit(10); //To use the setLimit() method in a scoped application, use the corresponding scoped method: setLimit().

GlideUpdateManager2 Push the update into the current update set


Recursive function (Update set)

//SAMPLE 1
//Query for the record
var rec = new GlideRecord('sys_portal');
rec.get('8a8df9f61be15d9088eceb17ec4bcb97');
//Push the record into the current update set  
var um = new GlideUpdateManager2();
um.saveRecord(rec);


//SAMPLE 2
var results = [];
var nestedCategories = ['898fc5a0db00d74074c99447db9619d8'];
getChildren(nestedCategories[0]);
searchItems();
return results;

function getChildren(sysID) {
  var gr = new GlideRecord('sc_category');
  gr.addQuery('parent', sysID);
  gr.addActiveQuery();
  gr.query();
  while(gr.next()) {
      var current = gr.sys_id.toString();
      nestedCategories.push(current);
      if(hasChildren(current)) {
          getChildren(current);
      }
  }
}

function hasChildren(sysID) {
  var gr = new GlideRecord('sc_category');
  gr.addQuery('parent', sysID);
  gr.addActiveQuery();
  gr.query();
  if(gr.next()) {
      return true;
  } else {
      return false;
  }
}

CatItem API

var catalogItemJS = new sn_sc.CatItem(sc.getUniqueValue());
if (!catalogItemJS.canView())
  continue;
var catItemDetails = catalogItemJS.getItemSummary();

CatCategory API

categoryJS = new sn_sc.CatCategory(data.category_id);
if (!categoryJS.canView()) {
  data.error = gs.getMessage("You do not have permission to see this category");
  return;
}

CatalogSearch API

var items = data.items = [];
var catalog = $sp.getValue('sc_catalog');
var sc = new sn_sc.CatalogSearch().search(catalog, data.category_id, '', false, options.depth_search);
sc.addQuery('sys_class_name', 'NOT IN', 'sc_cat_item_wizard');
if (data.keywords)
  sc.addQuery('123TEXTQUERY321', data.keywords);
sc.orderBy('order');
sc.orderBy('name');
sc.query();

Template

Description

// code here 
console.log("hello world");

About

Servicenow code snippets and translated documentation from pt-br

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 100.0%