GlideRecord - Global

GlideRecord is used for database operations.

A GlideRecord contains both records and fields. For information about GlideRecordSecure, which is a class inherited from GlideRecord that performs the same functions as GlideRecord, and also enforces ACLs, see the Using GlideRecordSecure.

Always test queries on a sub-production instance prior to deploying them on a production instance. An incorrectly constructed encoded query, such as including an invalid field name, produces an invalid query. When the invalid query is run, the invalid part of the query condition is dropped, and the results are based on the valid part of the query, which may return all records from the table. Using an insert(), update(), deleteRecord(), or deleteMultiple() method on bad query results can result in data loss.

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

GlideRecord - addActiveQuery()

Adds a filter to return active records.

Always test queries on a sub-production instance prior to deploying them on a production instance. An incorrectly constructed encoded query, such as including an invalid field name, produces an invalid query. When the invalid query is run, the invalid part of the query condition is dropped, and the results are based on the valid part of the query, which may return all records from the table. Using an insert(), update(), deleteRecord(), or deleteMultiple() method on bad query results can result in data loss.

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

Table 1. Parameters
Name Type Description
None
Table 2. Returns
Type Description
QueryCondition Filter to return active records

Scoped equivalent

To use the addActiveQuery() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - addActiveQuery().

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

GlideRecord - addDomainQuery(Object glideRecord)

Changes the domain used for the query from the user's domain to the domain of the provided GlideRecord.

Always test queries on a sub-production instance prior to deploying them on a production instance. An incorrectly constructed encoded query, such as including an invalid field name, produces an invalid query. When the invalid query is run, the invalid part of the query condition is dropped, and the results are based on the valid part of the query, which may return all records from the table. Using an insert(), update(), deleteRecord(), or deleteMultiple() method on bad query results can result in data loss.

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

Table 3. Parameters
Name Type Description
glideRecord Object GlideRecord from which to obtain the domain.
Table 4. Returns
Type Description
void

Scoped equivalent

This method is not available in scoped applications.

//This example requires the Domain plugin be active, the Group table is the specified 
//Domain table, and the ITIL user is in the Database Atlanta domain
//From any domain (using queryNoDomain()) look up the incidents that an ITIL user can only see 
//who is in the Database Atlanta domain, should expect all incidents with the global or the
//Database Atlanta domain specified.
var domain = new GlideRecord('sys_user');
domain.addQuery('user_name', 'itil');
domain.queryNoDomain();
if (domain.next()) {
    var domainQuery = new GlideRecord('incident');
    domainQuery.addQuery('active', true);
    domainQuery.addDomainQuery(domain);
    domainQuery.query();
    gs.print('Number of Incidents for ITIL user: ' + domainQuery.getRowCount());
    while (domainQuery.next())
        gs.print(domainQuery.number);
}

GlideRecord - addEncodedQuery(String query)

Adds an encoded query to other queries that may have been set.

Always test queries on a sub-production instance prior to deploying them on a production instance. An incorrectly constructed encoded query, such as including an invalid field name, produces an invalid query. When the invalid query is run, the invalid part of the query condition is dropped, and the results are based on the valid part of the query, which may return all records from the table. Using an insert(), update(), deleteRecord(), or deleteMultiple() method on bad query results can result in data loss.

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

Table 5. Parameters
Name Type Description
query String An . encoded query string.
Table 6. Returns
Type Description
void

Scoped equivalent

To use the addEncodedQuery() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - addEncodedQuery(String query).

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

GlideRecord - addInactiveQuery()

Adds a filter to return inactive records. Inactive records have the active flag set to false.

Always test queries on a sub-production instance prior to deploying them on a production instance. An incorrectly constructed encoded query, such as including an invalid field name, produces an invalid query. When the invalid query is run, the invalid part of the query condition is dropped, and the results are based on the valid part of the query, which may return all records from the table. Using an insert(), update(), deleteRecord(), or deleteMultiple() method on bad query results can result in data loss.

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

Table 7. Parameters
Name Type Description
None
Table 8. Returns
Type Description
QueryCondition Records where the active flag is false.

Scoped equivalent

In scoped applications use the scoped method Scoped GlideRecord - addQuery(String name, Object value).

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

GlideRecord - addJoinQuery(String table)

Adds a filter to return records based on a relationship in a related table.

For example, find all the users that are in the database group (users via sys_user_grmember table). Another example would be find all problems that have an assigned incident (problems via the incident.problem_id relationship).

This is not a true database join; rather, addJoinQuery() adds a subquery. So, while the result set is limited based on the join, the only fields that you have access to are those on the base table (those which are in the table with which the GlideRecord was initialized).

Always test queries on a sub-production instance prior to deploying them on a production instance. An incorrectly constructed encoded query, such as including an invalid field name, produces an invalid query. When the invalid query is run, the invalid part of the query condition is dropped, and the results are based on the valid part of the query, which may return all records from the table. Using an insert(), update(), deleteRecord(), or deleteMultiple() method on bad query results can result in data loss.

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

Table 9. Parameters
Name Type Description
table String Table name
Table 10. Returns
Type Description
QueryCondition Records where the relationships match.

Scoped equivalent

To use the addJoinQuery() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - addJoinQuery(String joinTable, Object primaryField, Object joinTableField).

Find problems that have an incident attached. This example returns problems that have associated incidents. However, it won't pull values from the incidents that are returned as a part of the query.

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

Find active=false problems with associated incidents.

// Look for Problem records
var gr = new GlideRecord('problem');
 
// That have associated Incident records
var grSQ = gr.addJoinQuery('incident');
 
// Where the Problem records are "active=false"
gr.addQuery('active', 'false');
 
// And the Incident records are "active=true"
grSQ.addCondition('active', 'true');
 
// Query
gr.query();
 
// Iterate and print results
while (gr.next()) {
    gs.print(gr.getValue('number'));
}

GlideRecord - addJoinQuery(String table, String primaryField)

Adds a filter to return records based on a relationship in a related table.

For example, find all the users that are in the database group (users via sys_user_grmember table). Another example would be find all problems that have an assigned incident (problems via the incident.problem_id relationship).

This is not a true database join; rather, addJoinQuery() adds a subquery. So, while the result set is limited based on the join, the only fields that you have access to are those on the base table (those which are in the table with which the GlideRecord was initialized).

Always test queries on a sub-production instance prior to deploying them on a production instance. An incorrectly constructed encoded query, such as including an invalid field name, produces an invalid query. When the invalid query is run, the invalid part of the query condition is dropped, and the results are based on the valid part of the query, which may return all records from the table. Using an insert(), update(), deleteRecord(), or deleteMultiple() method on bad query results can result in data loss.

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

Table 11. Parameters
Name Type Description
table String Table name
primaryField String If other than sys_id, the primary field.
Table 12. Returns
Type Description
QueryCondition Records where the relationships match.

Scoped equivalent

To use the addJoinQuery() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - addJoinQuery(String joinTable, Object primaryField, Object joinTableField).


      
    

GlideRecord - addJoinQuery(String table, String primaryField, String joinTableField)

Adds a filter to return records based on a relationship in a related table.

For example, find all the users that are in the database group (users via sys_user_grmember table). Another example would be find all problems that have an assigned incident (problems via the incident.problem_id relationship).

This is not a true database join; rather, addJoinQuery() adds a subquery. So, while the result set is limited based on the join, the only fields that you have access to are those on the base table (those which are in the table with which the GlideRecord was initialized).

Always test queries on a sub-production instance prior to deploying them on a production instance. An incorrectly constructed encoded query, such as including an invalid field name, produces an invalid query. When the invalid query is run, the invalid part of the query condition is dropped, and the results are based on the valid part of the query, which may return all records from the table. Using an insert(), update(), deleteRecord(), or deleteMultiple() method on bad query results can result in data loss.

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

Table 13. Parameters
Name Type Description
table String Table name
primaryField String If other than sys_id, the primary field.
joinTableField String If other than sys_id, the field that joins the tables
Table 14. Returns
Type Description
QueryCondition Records where the relationships match.

Scoped equivalent

To use the addJoinQuery() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - addJoinQuery(String joinTable, Object primaryField, Object joinTableField).

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();

GlideRecord - addNotNullQuery(String fieldName)

Adds a filter to return records where the specified field is not null.

Table 15. Parameters
Name Type Description
fieldName String The field name.
Table 16. Returns
Type Description
QueryCondition QueryCondition of records where the parameter field is not null.

Scoped equivalent

To use the addNotNullQuery() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - 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
  }

GlideRecord - addNullQuery(String fieldName)

Adds a filter to return records where the specified field is null.

Table 17. Parameters
Name Type Description
fieldName String The field name.
Table 18. Returns
Type Description
QueryCondition QueryCondition of records where the specified field is null.

Scoped equivalent

To use the addNullQuery() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - 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
  }

GlideRecord - addQuery(String name, Object operator, Object value)

Provides the ability to build a request, which when executed, returns the rows from the specified table, that match the request.

If you are familiar with SQL, this method is similar to the "where" clause. One or more addQuery() calls can be made in a single query; in this case the queries are AND'ed. If any of the query statements need to be OR'ed, use the GlideQueryCondition - Global class.

addQuery() is typically called with three parameters; table field, operator, and comparison value. It can be called with only two parameters, table field and comparison value, such as myObj.addQuery('category','Hardware');. The operator in this case is assumed to be "equal to".

Always test queries on a sub-production instance prior to deploying them on a production instance. An incorrectly constructed encoded query, such as including an invalid field name, produces an invalid query. When the invalid query is run, the invalid part of the query condition is dropped, and the results are based on the valid part of the query, which may return all records from the table. Using an insert(), update(), deleteRecord(), or deleteMultiple() method on bad query results can result in data loss.

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

Table 19. Parameters
Name Type Description
name String Table field name
operator Object Query operator. The available values are dependent on the data type of the value parameter.
Numbers:
  • =
  • !=
  • >
  • >=
  • <
  • <=
Strings (must be in upper case):
  • =
  • !=
  • IN
  • NOT IN
  • STARTSWITH
  • ENDSWITH
  • CONTAINS
  • DOES NOT CONTAIN
  • INSTANCEOF
value Object Value on which to query (not case-sensitive).
Table 20. Returns
Type Description
QueryCondition A reference to the QueryCondition that was added to the GlideRecord.

Scoped equivalent

To use the addQuery() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - addQuery(String name, String 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();
}

Using the IN operator.

var que = new GlideRecord('incident');
que.addQuery('number','IN','INC00001,INC00002');
que.query();
while(que.next()) {
 //do something....
}

GlideRecord - applyTemplate(String template)

Apply a template record (from sys_template) to the current record. If the specified template is not found, no action is taken.

Table 21. Parameters
Name Type Description
template String Name of a template from the sys_template table
Table 22. Returns
Type Description
void
var rec1 = new GlideRecord("incident");
rec1.initialize();
rec1.applyTemplate("my_incident_template");
//...possibly more code here... 

rec1.insert();

GlideRecord - autoSysFields(Boolean e)

Enables or disables the update to the fields sys_updated_by, sys_updated_on, sys_mod_count, sys_created_by, and sys_created_on. This is often used for manually updating field values on a record while leaving historical information unchanged.

Note: This is not available for scoped apps, starting with the Fuji release. See the Scoped GlideRecord API Reference for a list of what APIs are available for scoped apps.
Caution: Use caution if you use this method. When you use this method the sys_mod_count field will not be incremented, and other sys_ fields will not be updated. This can break functionality including, but not limited to, the Activity Formatter, History Sets, and Metrics.
Table 23. Parameters
Name Type Description
e Boolean If false disables updates to sys_updated_by, sys_updated_on, sys_mod_count, sys_created_by, and sys_created_on.
Table 24. Returns
Type Description
void

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();
}

GlideRecord - canCreate()

Determines if the access control rules (which includes the user's role) permit inserting new records in this table.

Table 25. Parameters
Name Type Description
None
Table 26. Returns
Type Description
Boolean True if the user's role permits creation of new records in the table.

Scoped equivalent

To use the canCreate() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - canCreate().

GlideRecord - canDelete()

Determines if the access control rules (which includes the user's role) permit deletion of records in this table.

Table 27. Parameters
Name Type Description
None
Table 28. Returns
Type Description
Boolean True if the user can delete records from this table, false otherwise.

Scoped equivalent

To use the canDelete() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - canDelete().

var att = new GlideRecord('sys_attachment');
att.get('$[sys_attachment.sys_id]');
var sm = GlideSecurityManager.get();
var checkMe = 'record/sys_attachment/delete';
var canDelete = sm.hasRightsTo(checkMe, att);
gs.log('canDelete: ' + canDelete);

GlideRecord - canRead()

Determines if the access control rules (which includes the user's role) permit reading this table.

Table 29. Parameters
Name Type Description
None
Table 30. Returns
Type Description
Boolean True if the user can read from this table, false otherwise.

Scoped equivalent

To use the canRead() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - canRead().


      
    

GlideRecord - canWrite()

Determines if the access control rules (which includes the user's role) permit updates to records in this table.

Table 31. Parameters
Name Type Description
None
Table 32. Returns
Type Description
Boolean True if the user can write to the table, false otherwise.

Scoped equivalent

To use the canWrite() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - canWrite().


      
    

GlideRecord - changes()

Determines whether any of the fields in the record have changed.

Table 33. Parameters
Name Type Description
None
Table 34. Returns
Type Description
Boolean True if any of the fields in the record have changed, false otherwise.

Scoped equivalent

To implement this functionality in a scoped application, add code similar to the following:

var gr = new GlideRecord("incident");
   gr.get("965c9e5347c12200e0ef563dbb9a7156");
   gr.short_description = "test";
   var elements = gr.getElements();
   var hasChanged = false;
   for(var i=0; i < elements.length;i++){
     var element = elements[i];
     hasChanged = hasChanged || element.changes();
     gs.info(element.getName() + ":" + element.changes());
   }
   gs.info(hasChanged);

      
    

GlideRecord - deleteMultiple()

Deletes multiple records according to the current "where" clause.

This method does not delete attachments.

Dot-walking is not supported for this method. When using the deleteMultiple() function on referenced tables, all the records in the table are deleted. Also, when using deleteRecord() to cascade delete, prior calls to setWorkflow() on the same GlideRecord object are ignored.

Do not use deleteMultiple() on tables with currency fields. Always delete each record individually. Also, do not use this method with the chooseWindow() or setLimit() methods when working with large tables.

Table 35. Parameters
Name Type Description
None
Table 36. Returns
Type Description
void

Scoped equivalent

To use the deleteMultiple() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - deleteMultiple().

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();

GlideRecord - deleteRecord()

Deletes a single record.

Note: When using deleteMultiple() to cascade delete, prior calls to setWorkflow() on the same GlideRecord object are ignored.
Table 37. Parameters
Name Type Description
None
Table 38. Returns
Type Description
Boolean True if the record was deleted; false if none were found to delete.

Scoped equivalent

To use the deleteRecord() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - deleteRecord().

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

GlideRecord - find(String columnName, String value)

Returns true if any record has a matching value in the specified column. If found, it also moves to the first record that matches, essentially executing next() until the record is returned.

Table 39. Parameters
Name Type Description
columnName String Specifies the field name.
value String Specifies the value to check for in the specified field.
Table 40. Returns
Type Description
Boolean True if any record has a matching value in the specified field.

      
    

GlideRecord - get(Object name, Object value)

Creates a GlideRecord based on a specified 'name = value' pair.

If the value parameter is not specified, then the method assumes the name parameter contains the sys_id.

Note: If you only pass a single parameter into this method, and that parameter is not the sys_id, the system performs a search across multiple fields (sys_id, name, number, so on). This action causes the system to try to create multiple records, which fails, and generates "duplicate record" error messages. To fix this problem, modify your method call to either contain both parameters or ensure that the passed-in parameter is the sys_id.

This method is meant for the query of single records. Therefore, the system performs a 'next' operation on the record before returning.

Table 41. Parameters
Name Type Description
name Object Field name
value Object Optional. Value to match
Table 42. Returns
Type Description
Boolean

True = GlideRecord was created

False = GlideRecord was not created

Scoped equivalent

To use the get() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - get(Object name, Object value).

function kbWriteComment(id, comments) {
 var fb = new GlideRecord('kb_feedback');
 fb.initialize();
 fb.article = id;
 fb.comments = comments;
 fb.insert();
}
 
function kbGetText(id) {
 var gr = new GlideRecord('kb_knowledge');
 if (gr.get(id)) {
 gr.u_times_used = gr.u_times_used + 1;
 gr.u_last_used = gs.nowDateTime();
 gr.update();
 // return "Knowledge article " + gr.number + ":\n" +
 // "[code]" + gr.text + "[/code]";
 return gr.number;
 }

GlideRecord - getAttribute(String fieldName)

Returns the dictionary attributes for the specified field.

Table 43. Parameters
Name Type Description
fieldName String A field name
Table 44. Returns
Type Description
String The attribute values in a string.

Scoped equivalent

To use the getAttribute() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - getAttribute(String fieldName).

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

GlideRecord - getClassDisplayValue()

Returns the table's label.

Table 45. Parameters
Name Type Description
None
Table 46. Returns
Type Description
String The table's label

Scoped equivalent

To use the getClassDisplayValue() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - getClassDisplayValue().


      
    

GlideRecord - getDisplayValue()

Retrieves the display value for the current record.

Table 47. Parameters
Name Type Description
None
Table 48. Returns
Type Description
String Display value for the current record

Scoped equivalent

To use the getDisplayValue() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - getDisplayValue().

// list will contain a series of display values separated by a comma
  // array will be a javascript array of display values
  var list = current.watch_list.getDisplayValue();
  var array = list.split(",");
  for (var i=0; i < array.length; i++) {
     gs.print("Display value is: " + array[i]);
  }

GlideRecord - getED()

Returns the element's descriptor.

Table 49. Parameters
Name Type Description
None
Table 50. Returns
Type Description
GlideElementDescriptor The element's descriptor

Scoped equivalent

To use the getED() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - getED().

var totalCritical  = 0;
var filledCritical = 0;
var fields         = current.getFields();
 
gs.print(fields);
 
for (var num = 0; num < fields.size(); num++) {
 
	gs.print("RUNNING ARRAY VALUE " + num);
 
	var ed = fields.get(num).getED();
 
	if(ed.hasAttribute("tiaa_critical")) {
		gs.print("CRITICAL FIELD FOUND");
		totalCritical ++;
 
		if (!fields.get(num).isNil()) {
			filledCritical ++;
		}
	}
 
}
 
var answer = 0;
gs.print("TOTAL - " + totalCritical);
gs.print("FILLED - " + filledCritical);
 
if (filledCritical > 0 && totalCritical > 0) {
 
	var pcnt = (filledCritical/totalCritical)*100;
	answer = pcnt.toFixed(2);;
 
}
 
answer;

GlideRecord - getElement(String fieldName)

Retrieves the GlideElement for a specified field.

Table 51. Parameters
Name Type Description
fieldName String A field name
Table 52. Returns
Type Description
GlideElement A GlideElement object

Scoped equivalent

To use the getElement() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - getElement(String columnName).


      
    

GlideRecord - getEncodedQuery(Boolean b)

Retrieves the encoded query as a string.

Table 53. Parameters
Name Type Description
b Boolean
Table 54. Returns
Type Description
String The encoded query

Scoped equivalent

To use the getEncodedQuery() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - getEncodedQuery().


      
    

GlideRecord - getEscapedDisplayValue()

Retrieves the field value for the display field of the current record and adds escape characters for use in Jelly scripts.

Table 55. Parameters
Name Type Description
None
Table 56. Returns
Type Description
String Escaped value of display field.


      
    

GlideRecord - getFields()

Retrieves a Java ArrayList of fields in the current record.

Table 57. Parameters
Name Type Description
None
Table 58. Returns
Type Description
Java ArrayList Fields in the current record

// This can be run in "Scripts - Background" for demonstration purposes
 
// 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();
 
// Enumerate GlideElements in the GlideRecord object that have values
gs.print('Enumerating over all fields with values:');
for (var i = 0; i < fields.size(); i++) {
  var glideElement = fields.get(i);
  if (glideElement.hasValue()) {
    gs.print('  ' + glideElement.getName() + '\t' + glideElement);
  }
}
gs.print('');
 
// Get a specific GlideElement: number
gs.print('Getting the number field:');
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);
  }
}

GlideRecord - getLabel()

Returns the field's label.

Table 59. Parameters
Name Type Description
None
Table 60. Returns
Type Description
String The field's label

Scoped equivalent

To use the getLabel() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - getLabel().

template.print("Summary of Requested items:\n");  
var gr = new GlideRecord("sc_req_item");
gr.addQuery("request", current.sysapproval);
gr.query();
while(gr.next()) {
    var nicePrice = gr.price.toString();
    if (nicePrice != '') {
        nicePrice = parseFloat(nicePrice);
        nicePrice = nicePrice.toFixed(2);
    }
    template.print(gr.number + ":  " + gr.quantity + " X " + gr.cat_item.getDisplayValue() 
                     + " at $" + nicePrice + " each \n");
    template.print("    Options:\n");
    for (key in gr.variables) {
      var v = gr.variables[key];
      if(v.getGlideObject().getQuestion().getLabel() != '') {
         template.space(4);
         template.print('     ' +  v.getGlideObject().getQuestion().getLabel() + " = " 
                     + v.getDisplayValue() + "\n");  
      }
    }
}

GlideRecord - getLocation(Boolean b)

Retrieves the current row number.

Table 63. Parameters
Name Type Description
b Boolean
Table 64. Returns
Type Description
Number The row number of the current record


      
    

GlideRecord - getPlural()

Retrieves the plural label of the GlideRecord table.

For example, if the table name is "Change Request," this method returns "Change Requests."

Table 65. Parameters
Name Type Description
None
Table 66. Returns
Type Description
String The plural label of the GlideRecord's table.


      
      

Output:

GlideRecord - getRecordClassName()

Retrieves the class (table) name for the current record.

Table 67. Parameters
Name Type Description
None
Table 68. Returns
Type Description
String Class or table name

Scoped equivalent

To use the getRecordClassName() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - getRecordClassName().

function TaskAssignmentFilter() {
  var classname = current.getRecordClassName();
  var filter = "type=null";
  if (classname == "incident" && current.category == "database") {
    filter = GetGroupFilter("database");
  }
  else {
    // append exclusion for 'catalog' to the filter
    var cat = new GlideRecord("sys_user_group_type");  
    cat.addQuery("name", "catalog");
    cat.query();
    if (cat.next()) {
      filter += "^ORtype!=" + cat.sys_id;
    }
  }
  gs.log("TaskAssignmentFilter: " + filter);
  return filter;
}

GlideRecord - getRelatedLists(Boolean b)

Retrieves a list of names and display values of tables that refer to the current record.

Table 69. Parameters
Name Type Description
Boolean b
Table 70. Returns
Type Description
HashMap Hash map with names and display values of related tables.


      
    

GlideRecord - getRelatedTables(Boolean b)

Retrieves a list of names and display values of tables that are referred to by the current record.

Table 71. Parameters
Name Type Description
b Boolean
Table 72. Returns
Type Description
HashMap Hash map with names and display values of related tables.


      
    

GlideRecord - getRowCount()

Retrieves the number of rows in the GlideRecord object.

Note: This method should be limited in use in a production environment as it creates a heavy load on the system.
Table 73. Parameters
Name Type Description
None
Table 74. Returns
Type Description
Number An integer count of the rows

Scoped equivalent

To use the getRowCount() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - getRowCount().


      
    

GlideRecord - getRowNumber()

Retrieves the row number set by saveLocation() or setLocation().

To get the current row number, use getLocation().

Table 75. Parameters
Name Type Description
None
Table 76. Returns
Type Description
Number The saved row number.


      
    

GlideRecord - getTableName()

Retrieves the table name associated with this GlideRecord.

Table 77. Parameters
Name Type Description
None
Table 78. Returns
Type Description
String A table name

Scoped equivalent

To use the getTableName() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - getTableName().

gs.log('Table: ' + current.getTableName()); 
gs.log('Parent: ' + current.parent.sys_id); 
var item = new GlideRecord('sc_req_item'); 
item.addQuery('sys_id', current.parent.sys_id); 
item.query(); 
if(item.next()){ 
  for(var variable in item.variable_pool) { gs.log(variable); 
  var answer = eval ("item.variable_pool." + variable + ".getDisplayValue()");
gs.log(answer);}
}

GlideRecord - getValue(String fieldName)

Retrieves the string value of an underlying element in a field.

Table 79. Parameters
Name Type Description
fieldName String Name of a field
Table 80. Returns
Type Description
String The string value of the underlying element. Returns null if the field is empty, or the field does not exist.

Scoped equivalent

To use the getValue() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - getValue(String name).


      
    

GlideRecord - GlideRecord(String tableName)

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

Table 81. Parameters
Name Type Description
tableName String The table to be used.
var gr = new GlideRecord('incident');

GlideRecord - hasAttachments()

Determines if the current record has any attachments.

Table 82. Parameters
Name Type Description
None
Table 83. Returns
Type Description
Boolean True if the current record has attachments, false otherwise.

//Check for attachments and add link if there are any
  var attachment_link = '';
  var rec = new GlideRecord('sc_req_item');
  rec.addQuery('sys_id', current.request_item);
  rec.query();
  if(rec.next()){
    if(rec.hasAttachments()){
      attachment_link = gs.getProperty('glide.servlet.uri') + rec.getLink();
    }    
  }

GlideRecord - hasNext()

Determines if there are any more records in the GlideRecord.

Table 84. Parameters
Name Type Description
None
Table 85. Returns
Type Description
Boolean True if there are more records in the query set.

Scoped equivalent

To use the hasNext() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - hasNext().

if (gr.hasNext()) {
  dothis(); // found it, do it
} else {
  dothat(); // didn't find it
}
;

GlideRecord - initialize()

Creates an empty record suitable for population before an insert.

Table 86. Parameters
Name Type Description
None
Table 87. Returns
Type Description
void

Scoped equivalent

To use the initialize() method in a scoped application, use the corresponding scoped method:Scoped GlideRecord - initialize().

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

GlideRecord - insert()

Inserts a new record using the field values that have been set for the current record.

Table 88. Parameters
Name Type Description
None
Table 89. Returns
Type Description
String The sys_id of the inserted record, or null if the record is not inserted.

Scoped equivalent

To use the insert() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - insert().

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

GlideRecord - insertWithReferences()

Inserts a new record and also inserts or updates any related records with the information provided.

Additional information about the method that does not belong in the short description.

Table 90. Parameters
Name Type Description
None
Table 91. Returns
Type Description
String sys_id for the record inserted, or null if the record was not inserted.

If a reference value is not specified (as below), then a new user record is created with the provided first_name, 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, 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();
}

If a caller_id value is specified, then that caller_id is updated with the provided first_name, 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();
}

GlideRecord - instanceOf(String className)

Checks a table for the type\class of table.

Table 92. Parameters
Name Type Description
className String Name of a type or class of record.
Table 93. Returns
Type Description
Boolean True if table is an instance of the specified class.


      
    

GlideRecord - isNewRecord()

Determines whether the current record has been inserted into the database. This method returns true only if the newRecord() method has been called. This method is useful for scripted ACL, and in the condition of UI actions, but should not be used in background scripts.

Note: This method returns true for any new record during a business rule, or if the newRecord() method is used to initialize a record with default values and a unique ID (sys_id). In all other cases, it returns false.
Table 94. Parameters
Name Type Description
None
Table 95. Returns
Type Description
Boolean True if the current record is new (has not been inserted into the database.)

Scoped equivalent

To use the isNewRecord() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - isNewRecord().

answer = gs.hasRole("filter_admin") || current.isNewRecord()

GlideRecord - isValid()

Determines if the table exists.

Table 96. Parameters
Name Type Description
None
Table 97. Returns
Type Description
Boolean True if the table is valid or if the record was successfully fetched, false otherwise.

Scoped equivalent

To use the isValid() method in a scoped application, use the corresponding scoped method:Scoped GlideRecord - isValid().

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

GlideRecord - isValidField(String fieldName)

Determines if the specified field is defined in the current table.

Table 98. Parameters
Name Type Description
fieldName String Name of a field.
Table 99. Returns
Type Description
Boolean True if the field is valid, false otherwise.

Scoped equivalent

To use the isValidField() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - isValidField(String columnName).


      
    

GlideRecord - isValidRecord()

Determines if the current record is valid.

Table 100. Parameters
Name Type Description
None
Table 101. Returns
Type Description
Boolean True if the current record is valid or false if past the end of the record set.

Scoped equivalent

To use the isValidRecord() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - isValidRecord().


      
    

GlideRecord - newRecord()

Creates a GlideRecord, set the default values for the fields and assign a unique id to the record.

Table 102. Parameters
Name Type Description
None
Table 103. Returns
Type Description
void

Scoped equivalent

To use the newRecord() method in a scoped application, use the corresponding scoped method:Scoped GlideRecord - newRecord().


      
    

GlideRecord - next()

Moves to the next record in the GlideRecord.

Use this method to iterate through the records returned by a GlideRecord query.

Note: This method will fail if there is a field in the table called "next".
Note: The if(myObj.next()) construct only processes the first record returned.
Table 104. Parameters
Name Type Description
None
Table 105. Returns
Type Description
Boolean True if there are more records in the query set.

Scoped equivalent

To use the next() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - next().

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

GlideRecord - _next()

Moves to the next record in the GlideRecord. Provides the same functionality as next(), intended to be used in cases where the GlideRecord has a column named next.

Table 106. Parameters
Name Type Description
None
Table 107. Returns
Type Description
Boolean True if there are more records in the query set.

Scoped equivalent

To use the _next() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - _next().

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

GlideRecord - operation()

Retrieves the current operation being performed, such as insert, update, delete, etc.

Table 108. Parameters
Name Type Description
None
Table 109. Returns
Type Description
String The current operation

Scoped equivalent

To use the operation() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - operation().


      
    

GlideRecord - orderBy(String fieldName)

Specifies a field name to be used to order the query set. This may be called more than once to order by multiple fields.

Table 110. Parameters
Name Type Description
fieldName String A field name
Table 111. Returns
Type Description
void

Scoped equivalent

To use the orderBy() method in a scoped application, use the corresponding scoped method:Scoped GlideRecord - orderBy(String name).

function UpdateProjectWBS(project) {
  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');
}

GlideRecord - orderByDesc(String, fieldName)

Specifies a field used to order the query set in descending order.

Table 112. Parameters
Name Type Description
fieldName String A field name.
Table 113. Returns
Type Description
void

Scoped equivalent

To use the orderByDesc() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - orderByDesc(String name).


      
    

GlideRecord - query(Object field, Object value)

Runs the query against the table based on the filters specified by addQuery() and addEncodedQuery().

This will query the GlideRecord table as well as any references of the table. One argument adds a query string. Usually this is performed without arguments, but a name/value pair can be specified.

Table 114. Parameters
Name Type Description
name Object A field name
value Object A value
Table 115. Returns
Type Description
void

Scoped equivalent

To use the query() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - query(Object field, Object value).

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

GlideRecord - _query(Object field, Object value)

Identical to query(). This method is intended to be used on tables where there is a column named query, which would interfere with using the query() method.

Runs the query against the table based on the filters specified by the addQuery() and addEncodedQuery() methods. This will query the GlideRecord table as well as any references of the table. One argument adds a query string. Usually this is performed without arguments, but a name/value pair can be specified.

Table 116. Parameters
Name Type Description
name Object A field name
value Object A value
Table 117. Returns
Type Description
void

Scoped equivalent

To use the _query() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - _query(Object field, Object value).

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

GlideRecord - queryNoDomain(Object field, Object value)

Used in domain separated instances. Similar to query(), runs the query against the table based on the filters specified by addQuery() and addEncodedQuery(), but ignores domains.

This will query the GlideRecord table as well as any references of the table. One argument adds a query string. Usually this is performed without arguments, but a name/value pair can be specified.

Table 118. Parameters
Name Type Description
field Object A field name
value Object A value
Table 119. Returns
Type Description
void

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

GlideRecord - restoreLocation()

Sets the current record to be the record that was saved with saveLocation(). If saveLocation() has not been called, the current record is set to be the first record of the GlideRecord.

Table 120. Parameters
Name Type Description
None
Table 121. Returns
Type Description
void


      
    

GlideRecord - saveLocation()

Save the current row number so that we can get back to this location using the restoreLocation() method.

Table 122. Parameters
Name Type Description
None
Table 123. Returns
Type Description
void


      
    

GlideRecord - setAbortAction(Boolean b)

Sets a flag to indicate if the next database action (insert, update, delete) is to be aborted.

Table 124. Parameters
Name Type Description
b Boolean True to abort next action, or false to allow the next action.
Table 125. Returns
Type Description
void

Scoped equivalent

To use the setAbortAction() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - setAbortAction(Boolean b).

if ((!current.u_date1.nil()) && (!current.u_date2.nil())) {
  var start = current.u_date1.getGlideObject().getNumericValue();
  var end = current.u_date2.getGlideObject().getNumericValue();
  if (start > end) {
    gs.addInfoMessage('start must be before end');
    current.u_date1.setError('start must be before end');
    current.setAbortAction(true);
  }
}

GlideRecord - setDisplayValue(String name, Object value)

Sets the specified field to the specified display value.

For a reference field this is the display value for the table. For a date/time this is the time in the caller's current timezone.

Table 126. Parameters
Name Type Description
name String Field name
value Object Display value for the specified field.
Table 127. Returns
Type Description
void

var gr = new GlideRecord('incident');
gr.get('46f09e75a9fe198100f4ffd8d366d17b');
gr.setDisplayValue('opened_at','2011-02-13 4:30:00');
gr.update();

GlideRecord - setForceUpdate(Boolean force)

Updates the record even if fields have not changed.

Table 128. Parameters
Name Type Description
force Boolean True to update even if fields have not changed, otherwise false.
Table 129. Returns
Type Description
void


      
    

GlideRecord - setLimit(Number limit)

Sets the limit for how many records are in the GlideRecord.

Table 130. Parameters
Name Type Description
limit Number Limit for records to fetch.
Table 131. Returns
Type Description
void

Scoped equivalent

To use the setLimit() method in a scoped application, use the corresponding scoped method:Scoped GlideRecord - setLimit(Number maxNumRecords).

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

GlideRecord - setLocation(Number rowNumber)

Sets the current row location.

Table 132. Parameters
Name Type Description
rowNumber Number The row number to set as the current row.
Table 133. Returns
Type Description
void


      
    

GlideRecord - setNewGuid()

Generates a new GUID and sets it as the unique id for the current record. This function applies only to new records. The GUID for an existing record cannot be changed

Table 134. Parameters
Name Type Description
None
Table 135. Returns
Type Description
void

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 gr = new GlideRecord ('task_rel_task');
//link the incident to the request (may need to review if it needs to be the item)
gr.parent = current.request;
gr.child = tsk_id;
gr.insert();

GlideRecord - setNewGuidValue (String guid)

Generates a new GUID and sets it as the unique id for the current record, when inserting a new record.

Table 136. Parameters
Name Type Description
guid String A string value for the new GUID
Table 137. Returns
Type Description
void

Scoped equivalent

To use the setNewGuidValue() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - setNewGuidValue(String guid).


      
    

GlideRecord - setQueryReferences(Boolean queryReferences)

Enables or disables using the reference field's display name when querying a reference field.

Table 138. Parameters
Name Type Description
queryReferences Boolean If true, will generate a string of display names. If false, will generate a string of sys_ids.
Table 139. Returns
Type Description
void


      
    

GlideRecord - setUseEngines(Boolean e)

Disable or enable the running of any engines (approval rules / assignment rules).

Table 140. Parameters
Name Type Description
e Boolean If true, enables engines. If false disables engines.
Table 141. Returns
Type Description
void


      
    

GlideRecord - setValue(String name, Object value)

Sets the specified field to the specified value.

Normally a script would do a direct assignment, for example, gr.category = value. However, if in a script the element name is a variable, then gr.setValue(elementName, value) can be used. When setting a value, ensure the data type of the field matches the data type of the value you enter. This method cannot be used on journal fields.

If the value parameter is null, the record is not updated, and an error is not thrown.

Table 142. Parameters
Name Type Description
name String Field name
value Object A value to be assigned.
Table 143. Returns
Type Description
void

Scoped equivalent

To use the setValue() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - setValue(String name, Object value).


      
    

GlideRecord - setWorkFlow(Boolean e)

Enables or disables the running of business rules that might normally be triggered by subsequent actions. If the e parameter is set to false, an insert/update will not be audited. Auditing only happens when the parameter is set to true for a GlideRecord operation.

Note: The setWorkFlow() method is ignored when subsequently using either the deleteProblem() or deleteMultiple() methods to cascade delete.
Table 144. Parameters
Name Type Description
e Boolean If true (default) enables business rules, and if false to disables them.
Table 145. Returns
Type Description
void

Scoped equivalent

To use the setWorkFlow() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - setWorkflow(Boolean enable).

doit('name1','name2'); 
 
function doit(username1,username2) { 
 
  var usr1 = new GlideRecord('sys_user');
  var usr2 = new GlideRecord('sys_user');
  var num = 0;
 
  if (usr1.get('user_name',username1) && usr2.get('user_name',username2)) {
    var ref;
    var dict = new GlideRecord('sys_dictionary');
    dict.addQuery('reference','sys_user');
    dict.addQuery('internal_type','reference');
    dict.query();
    while (dict.next()) {
      num = 0;
      ref = new GlideRecord(dict.name.toString());
      ref.addQuery(dict.element,usr1.sys_id);
      ref.query();
      while (ref.next()) {
        ref.setValue(dict.element.toString(),usr2.sys_id); 
        ref.setWorkflow(false);
        ref.update();
        num++;
      }
      if (num > 0) {
        gs.print(dict.element + ' changed from ' + usr1.user_name + 
          ' to ' + usr2.user_name + ' in ' + num + ' ' + dict.name + ' records');
      }
    }
  }
}

GlideRecord - update(Object reason)

Updates the GlideRecord with any changes that have been made. If the record does not exist, it is inserted.

Table 146. Parameters
Name Type Description
reason Object A string designating the reason for the update. The reason is displayed in the audit record.
Table 147. Returns
Type Description
String Unique id of the new or update record. Returns null if the update fails.

Scoped equivalent

To use the update() method in a scoped application, use the corresponding scoped method: Scoped GlideRecord - update(String reason).

  var gr = new GlideRecord('task_ci');
gr.addQuery();
gr.query();
var count = gr.getRowCount();
if (count > 0) {
   var allocation = parseInt(10000 / count) / 100;
   while (gr.next()) {
      gr.u_allocation = allocation;
      gr.update();
   }
}

GlideRecord - updateWithReferences(Object reason)

Updates a record and also inserts or updates any related records with the information provided.

Table 148. Parameters
Name Type Description
reason Object A string designating the reasons for the updates. The reason is displayed in the audit record.
Table 149. Returns
Type Description
String The sys_id for the record being updated.

If processing an incident where the Caller ID is set to reference sys_user record 'David Loo,' then the following code would update David Loo'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();
}