ServiceNow-ATF

GlideRecord

// 1. Create an object to store rows from a table
var myObj = new GlideRecord('table_name');

// 2. Build query
myObj.addQuery('field_name','operator','value');
myObj.addQuery('field_name','operator','value');

// 3. Execute query 
myObj.query();

// 4. Process returned records
while(myObj.next()){
  //Logic you want to execute.  
  //Use myObj.field_name to reference record fields
}

There is a client-side GlideRecord API for global applications.

The client-side GlideRecord API cannot be used in scoped applications.

Build the Query Condition(s)

You can set the glide.invalid_query.returns_no_rows system property to true to have queries with invalid encoded queries return no records.

Iterating through Returned Records

// iterate through all records in the GlideRecord and set the Priority field value to 4 (low priority).
// update the record in the database
while(myObj.next()){
  myObj.priority = 4;
  myObj.update(); 
}
// Set the Priority field value to 4 (low priority) for the first record in the GlideRecord
// update the record in the database
if(myObj.next()){
  myObj.priority = 4;
  myObj.update(); 
}
// When using updateMultiple(), use the setValue() method.  
// Using myObj.priority = 4 may return unexpected results.
myObj.setValue('priority',4);
myObj.updateMultiple();

Counting Records in a GlideRecord

// If you need to know the row count for a query on a production instance do this
var count = new GlideAggregate('x_snc_needit_needit'); 
count.addAggregate('COUNT'); 
count.query(); 
var recs = 0; 
  if (count.next()){ 
    recs = count.getAggregate('COUNT');
  }
gs.info("Returned number of rows = " +recs);
// Do not do this on a production instance. 
var myObj = new GlideRecord('x_snc_needit_needit');
myObj.query();
gs.info("Returned record count = " + myObj.getRowCount());

Encoded Queries

var myObj = new GlideRecord("x_snc_needit_needit");
myObj.addEncodedQuery('<your_encoded_query>');
myObj.query();
while(myObj.next()){
  // Logic you want to execute for the GlideRecord records
}

Be sure to enclose the encoded query in “” or ‘’.

var myObj = new GlideRecord("x_snc_needit_needit");
myObj.addEncodedQuery("u_when_neededBETWEENjavascript:gs.daysAgoStart(0)@javascript:gs.quartersAgoEnd(1)^active=true^state=14^ORstate=16");
  myObj.query();
  while(myObj.next()){
    // Insert logic you want to execute for the GlideRecord records
  }

Retrieve values from records

GlideRecordSecure

GlideRecord API

GlideRecord(String tableName)

Creates an instance of the GlideRecord class for the specified table.

var now_GR = new GlideRecord('incident');

addActiveQuery()

var inc = new GlideRecord('incident');
inc.addActiveQuery();
inc.query();

addInactiveQuery()

var inc = new GlideRecord('incident');
inc.addInactiveQuery();
inc.query();

addNotNullQuery(String fieldName)

var target = new GlideRecord('incident'); 
  target.addNotNullQuery('short_description');
  target.query();   // Issue the query to the database to get all records
  while (target.next()) {   
     // add code here to process the incident record
  }

addNullQuery(String fieldName)

var target = new GlideRecord('incident'); 
  target.addNullQuery('short_description');
  target.query();   // Issue the query to the database to get all records
  while (target.next()) {   
     // add code here to process the incident record
  }

addQuery(String name, Object operator, Object value)

var rec = new GlideRecord('incident');
rec.addQuery('active',true);
rec.addQuery('sys_created_on', ">", "2010-01-19 04:05:00");
rec.query();
while (rec.next()) { 
 rec.active = false;
 gs.print('Active incident ' + rec.number + ' closed');
 rec.update();
}
var que = new GlideRecord('incident');
que.addQuery('number','IN','INC00001,INC00002');
que.query();
while(que.next()) {
 //do something....
}

If any of the query statements need to be OR’ed

addCondition(String name, String oper, Object value)
var now_GR = new GlideRecord('incident');
var qc = now_GR.addQuery('category', 'Hardware');
qc.addCondition('category', 'Network');
now_GR.addQuery('number','INC0000003');
now_GR.next();
now_GR.number;
gs.info(now_GR.getEncodedQuery());
addOrCondition(String name, String oper, Object value)
var now_GR = new GlideRecord('incident');
var qc = now_GR.addQuery('category', 'Hardware');
qc.addOrCondition('category', 'Network');
now_GR.addQuery('number','INC0000003');
now_GR.next();
now_GR.number;
gs.info(now_GR.getEncodedQuery());
var myObj = new GlideRecord('incident');
var q1 = myObj.addQuery('state', '<', 3);
q1.addOrCondition('state', '>', 5);
var q2 = myObj.addQuery('priority', 1);
q2.addOrCondition('priority', 5);
myObj.query();

addEncodedQuery(String query, Boolean enforceFieldACL)

var queryString = "priority=1^ORpriority=2";
 var now_GR = new GlideRecord('incident');
 
 now_GR.addEncodedQuery(queryString);
 now_GR.query();
 while (now_GR.next()) {
 gs.addInfoMessage(now_GR.number);
 }

applyEncodedQuery(String queryString)

function createAcl(table, role) {
  gs.print("Checking security on table " + table);
  var now_GR = new GlideRecord("sys_security_acl");
  now_GR.addQuery("name", table);
  now_GR.addQuery("operation", "read");
  now_GR.query();
  var encQuery = now_GR.getEncodedQuery();
  if (now_GR.next()) {
    // existing acl found so use it
    createAclRole(now_GR.sys_id.toString(), role);
    return;
  } else {
  now_GR.initialize();
  now_GR.applyEncodedQuery(encQuery);
  var acl = now_GR.insert();
    gs.print("Added read access control on " + table);
    createAclRole(acl, role);
  } 
}

getEncodedQuery()

 var now_GR = new GlideRecord("sys_security_acl");
  now_GR.addQuery("name", table);
  now_GR.addQuery("operation", "read");
  now_GR.query();
  var encQuery = now_GR.getEncodedQuery();

addExtraField(String dotWalkedField)

var gliderecord = new GlideRecord("incident");
gliderecord.addQuery("number", "INC0041457");
gliderecord.addExtraField("cmdb_ci.location.contact.name");
gliderecord.query();
gliderecord.next();
gs.print(gliderecord.cmdb_ci.location.contact.name);

Note: The addExtraField() method does not impact output results; the output is always the same regardless if you use this method in your script.

addJoinQuery(String table)

var prob = new GlideRecord('problem');
prob.addJoinQuery('incident');
prob.query();

addJoinQuery(String table, String primaryField)

var now_GR = new GlideRecord('problem'); 
now_GR.addJoinQuery('incident', 'opened_by'); 
now_GR.query();

addJoinQuery(String table, String primaryField, String joinTableField)

var now_GR = new GlideRecord('problem'); 
now_GR.addJoinQuery('incident', 'opened_by', 'caller_id'); 
now_GR.query();

addValue(String field, Number value)

gs.print(now_now_GR.u_count); // "1" 
now_GR.addValue("u_count", 1); 
now_GR.update(); 
now_GR.get(now_GR); // The record must be reloaded from the database to observe the result
gs.print(now_now_GR.u_count); // "3", if executed concurrently with another user 

Note: If setValue() is called for the specified field prior to calling addValue(), the addValue() method is not processed and an error message is logged.

applyTemplate(String template)

var rec1 = new GlideRecord("incident");
rec1.initialize();
rec1.applyTemplate("my_incident_template");
rec1.insert();

autoSysFields(Boolean e)

Warning: Use caution if you use this method.

var inc = new GlideRecord('incident');
 
// Change all Open(1) incidents to Active(2)
 
inc.addQuery('state', 1);
inc.query();
 
while (inc.next()) {
  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
  inc.setValue('state', 2);
  inc.update();
}

canCreate()

var now_GR = new GlideRecord('benefit_plan');
return now_GR.canCreate();

canDelete()

canRead()

var now_GR = new GlideRecord('benefit_plan');
return now_GR.canRead();

canWrite()

var now_GR = new GlideRecord('benefit_plan');
return now_GR.canWrite();

changes()

var now_GR = new GlideRecord("incident");
now_GR.query();
now_GR.next();
if (now_GR.changes()) {
  gs.print("The incident record reported changes right after being read");
} else {
  gs.print("The incident record has not changed");
}

deleteRecord()

var rec = new GlideRecord('incident');
rec.addQuery('active',false);
rec.query();
while (rec.next()) { 
 gs.info('Inactive incident ' + rec.number + ' deleted');
 rec.deleteRecord();
}

deleteMultiple()

var now_GR = new GlideRecord('incident');
now_GR.addQuery('active','false');
now_GR.query();
now_GR.deleteMultiple();

find(String columnName, String value)

var now_GR = new GlideRecord("incident");
now_GR.query();
var shortDescription = "Critical";
if (now_GR.find("short_description", shortDescription)) {
  gs.print("An incident with the specified field value was found");
  var recordID = now_GR.getValue("sys_id");
  gs.print("Found in the following record: " + recordID);
} else {
  gs.print("An incident with the specified field value was not found");
}

get(Object name, Object value)

var grIncident = new GlideRecord('incident');
var returnValue = grIncident.get('99ebb4156fa831005be8883e6b3ee4b9');
gs.info(returnValue); // logs true or false
gs.info(grIncident.number); // logs Incident Number
var grIncident = new GlideRecord('incident');
var returnValue = grIncident.get('caller_id.name','Sylivia Wayland');
gs.info(returnValue); // logs true or false
gs.info(grIncident.number); // logs Incident Number

getAttribute(String fieldName)

var now_GR = new GlideRecord('sys_user');
  now_GR.query("user_name","admin");
  if (now_GR.next()) {
    gs.print("we got one");
    gs.print(now_GR.location.getAttribute("tree_picker"));
  }

getClassDisplayValue()

// Display the incident table label
var now_GR = new GlideRecord("incident");
var value = now_GR.getClassDisplayValue();
gs.info("The table label is " + value + ".");

getDisplayValue(String name)

var now_GR = new GlideRecord('incident');
now_GR.get('sys_id','<sys_id>');
gs.info(now_GR.getDisplayValue());

getEscapedDisplayValue()

For this method to work, a display value must have been set on the associated table.

var escapeValue = now_GR.getEscapedDisplayValue();
gs.print("Escaped name: " + escapeValue);

getFields()

// Get a single incident record
var grINC = new GlideRecord('incident');
grINC.query();
grINC.next();
gs.print('Using ' + grINC.getValue('number'));
gs.print('');
 
// getFields() returns a Java ArrayList
var fields = grINC.getFields();

getLink(Boolean noStack)

getRecordClassName()

var classname = current.getRecordClassName();

getRelatedLists()

var now_GR = new GlideRecord('incident');
var c = now_GR.getRelatedLists().values().toArray();
var numElements = c.length;
for( var i = 0; i < numElements; ++i){
  gs.print(i+": "+c[i]);
}

getRelatedTables()

var now_GR = new GlideRecord('incident');
var c = now_GR.getRelatedTables().values().toArray();
var numElements = c.length;
for( var i = 0; i < numElements; ++i){
  gs.print(i+": "+c[i]);
}

getRowCount()

var numberOfIncidents = new GlideRecord('incident');
numberOfIncidents.query();
gs.info("Records in incident table: " + numberOfIncidents.getRowCount());

getTableName()

gs.log('Table: ' + current.getTableName()); 

getUniqueValue()

var now_GR = new GlideRecord('kb_knowledge');
now_GR.query();
now_GR.next();
var uniqueid = now_GR.getUniqueValue();
gs.info(uniqueid);

getValue(String fieldName)

hasAttachments()

hasNext()

initialize()

var now_GR = new GlideRecord('to_do');
now_GR.initialize(); 
now_GR.name = 'first to do item'; 
now_GR.description = 'learn about GlideRecord'; 
now_GR.insert();

newRecord()

var now_GR = new GlideRecord("sys_user");
now_GR.newRecord();
now_GR.setValue("user_name", "John Smith");
gs.print("Is this a new record: " + now_GR.isNewRecord());

insert()

instanceOf(String className)

insertWithReferences()

Examples

  1. If a reference value is not specified (as below), then a new user record is created with the provided first_name and last_name, and the caller_id value is set to this newly created sys_user record. The result is a new sys_user record with the provided first_name and last_name and a new incident record with the provided short_description and caller_id.
var inc = new GlideRecord('incident');
inc.initialize();
inc.short_description = 'New incident 1';
inc.caller_id.first_name = 'John';
inc.caller_id.last_name = 'Doe';
inc.insertWithReferences();
  1. If a caller_id value is specified, then that caller_id is updated with the provided first_name and last_name. The result is a newly created incident record with values set for short_description and caller_id.
var inc = new GlideRecord('incident');
inc.initialize();
inc.short_description = 'New incident 1';
inc.caller_id.setDisplayValue('David Loo');
inc.caller_id.first_name = 'John';
inc.caller_id.last_name = 'Doe';
inc.insertWithReferences();

isNewRecord()

var now_GR = new GlideRecord("sys_user");
now_GR.newRecord();
now_GR.setValue("user_name", "John Smith");
gs.print("Is this a new record: " + now_GR.isNewRecord());

var now_GR2 = new GlideRecord("sys_user");
now_GR2.addQuery("user_name", "Abel Tutor");
now_GR2.query();
now_GR2.next();
gs.print("Is this a new record: " + now_GR2.isNewRecord());

isValid()

var testTable = new GlideRecord('incident');
gs.print(testTable.isValid());

isValidField(String columnName)

si.isValidField('sys_class_name')

next()

var rec = new GlideRecord('incident');
rec.query();
while (rec.next()) { 
  gs.print(rec.number + ' exists');
}

This method fails if there is a field in the table called “next”. If that is the case, use the method _next().

_next()

var rec = new GlideRecord('sys_template');
rec.query();
while (rec._next()) { 
  gs.print(rec.number + ' exists');
}

orderBy(String fieldName)

var count = 0;
  var child = new GlideRecord('pm_project_task');
  child.addQuery('parent', project.sys_id);
  child.orderBy('order');
  child.orderBy('number');
  child.query();
  var len = child.getRowCount().toString().length;
  var seq = 0;
  while (child.next()) {
    count += UpdateProjectTaskWBS(child, 1, ++seq, len, '');
  }
  gs.addInfoMessage(count + ' Project Tasks updated');

orderByDesc(String, fieldName)

query(String field, String value)

setAbortAction(Boolean b)

current.setAbortAction(true);

setLimit(Number limit)

var now_GR = new GlideRecord('incident');
now_GR.orderByDesc('sys_created_on');
now_GR.setLimit(10);
now_GR.query();

setNewGuid()

var task = new GlideRecord ('task');
var tsk_id = task.setNewGuid();
 
task.description = "Request: " + current.request.number;
task.description = task.description + "\n" + "Requested by: " + current.request.u_requested_by.name;
task.description = task.description + "\n" + "Requested for: " + current.request.u_requested_for.name;
task.description = task.description + "\n" + "Item: " + current.cat_item.name;
 
var now_GR = new GlideRecord ('task_rel_task');
//link the incident to the request
now_GR.parent = current.request;
now_GR.child = tsk_id;
now_GR.insert();

setNewGuidValue (String guid)

ci.setNewGuidValue(sys_id);

setUseEngines(Boolean e)

var now_GR = new GlideRecord("oauth_credential");
  var oauthClient = now_GR.addJoinQuery("oauth_entity", "peer", "sys_id");
  now_GR.addQuery("type", "access_token");
  now_GR.addQuery("expires", ">", nowDateTime());
  now_GR.addNullQuery("oauth_requestor_profile");
  oauthClient.addCondition("active", "true");
  oauthClient.addCondition("type", "client");
  now_GR.setUseEngines(false);
  now_GR.setWorkflow(false);
  now_GR.query();
  return now_GR.hasNext();

setValue(String name, Object value)

setWorkflow(Boolean e)

update(Object reason)

updateMultiple()

var now_GR = new GlideRecord('incident');
now_GR.addQuery('active', true);
now_GR.setValue('state',  4);
now_GR.updateMultiple();

updateWithReferences(Object reason)

If processing an incident where the Caller ID is set to reference sys_user record ‘John Doe,’ then the following code would update John Doe’s user record. If processing an incident where there is no Caller ID specified, then the following code would create a new sys_user record with the provided information (first_name, last_name) and set the Caller ID value to the newly created sys_user record.

var inc = new GlideRecord('incident');
inc.get(inc_sys_id);  // Looking up an existing incident record where 'inc_sys_id' represents the sys_id of a incident record
inc.caller_id.first_name = 'John';
inc.caller_id.last_name = 'Doe';
inc.updateWithReferences();
}

setJournalEntry(String entry, String userName)

var now_GR = new GlideRecord("incident");

now_GR.addQuery("sys_id", "<sys_id_value>");
now_GR.query();

if(now_GR.next()){
  now_GR.work_notes.setJournalEntry("Content of the journal entry.", "abel.tuter");  
  now_GR.update();
}

getJournalEntry(Number mostRecent)

var notes = current.work_notes.getJournalEntry(-1); 

References:

  1. Server-side Scripting
  2. GlideRecord
  3. GlideRecord - Global
  4. GlideElement
  5. GlideQueryCondition