GlideRecord

From ServiceNow Wiki
Home > Script > Server APIs > Glide Server APIs > GlideRecord
Jump to: navigation, search
Scripting Glide and Jelly
Related Topics
Knowledge.gif Get the Glide Reference Book


1 Overview

GlideRecord is a special Java class (GlideRecord.java) that can be used in JavaScript exactly as if it was a native JavaScript class.

GlideRecord

  • is used for database operations instead of writing SQL queries.
  • is an object that contains zero or more records from one table. Another way to say this is that a GlideRecord is an ordered list.
Note
Note: The global Glide APIs are not available in scoped scripts. There are scoped Glide APIs for use in scoped scripts. The scoped Glide APIs provide a subset of the global Glide API methods. For information on scoped applications see Application Scope, scripting in scoped applications, and the list of scoped APIs.


Use this API to:


A GlideRecord contains both records (rows) and fields (columns). The field names are the same as the underlying database column names.

For more information on available JavaScript operators and additional GlideRecord examples, see Using GlideRecord to Query Tables.

2 Query

Query Method Summary
Return Value Details
QueryCondition addActiveQuery()
Adds a filter to return active records.
void addDomainQuery(Object o)
Changes the domain used for the query from the user's domain to the domain of the provided GlideRecord.
void addEncodedQuery(String query)
Adds an encoded query. Adds an encoded query to the other queries that may have been set.
QueryCondition addInactiveQuery()
Adds a filter to return inactive records.
QueryCondition addJoinQuery(joinTable, [primaryField], [joinTableField])
Adds a filter to return records based on a relationship in a related table.
QueryCondition addNotNullQuery(String fieldName)
Adds a filter to return records where the specified field is not null.
Query Condition addNullQuery(String fieldName)
Adds a filter to return records where the specified field is null.
QueryCondition addOrCondition(String fieldName, Object operator, Object value)
Adds an alternative filter to an existing query to return records based on 1, 2 or 3 arguments.
  • 1 argument adds an encoded query string.
  • 2 arguments return records where the field is equal to the value (or is in a list of values).
  • 3 arguments return records where the field meets the specified condition (field, operator and value).
QueryCondition addQuery(String fieldName, Object operator, Object value)
Adds a filter to return records based on 1, 2 or 3 arguments.
  • 1 argument adds an encoded query string.
  • 2 arguments return records where the field is equal to the value (or is in a list of values).
  • 3 arguments return records where the field meets the specified condition (field, operator and value).
boolean canCreate()
Determines if the Access Control Rules (which includes the user's role) permit inserting new records in this table.
boolean canDelete()
Determines if the Access Control Rules (which includes the user's role) permit deletion of records in this table.
boolean canRead()
Determines if the Access Control Rules (which includes the user's role) permit reading this table.
boolean canWrite()
Determines if the Access Control Rules (which includes the user's role) permit updates to records in this table.
boolean changes()
Determines whether any of the fields in the record have changed.
boolean find(columnName, 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.
boolean hasAttachments()
Determines if the current record has any attachments.
boolean hasNext()
Determines if there are any more records in the GlideRecord.
boolean instanceOf(String className)
Checks a table for a type/class of record.
boolean isNewRecord()
Determines whether the current record has been inserted into the database.
boolean isValid()
Determines whether the table exists or not.
boolean isValidField(String columnName)
Determines if the given field is defined in the current table.
boolean isValidRecord()
Determine if there is another record in the GlideRecord.
boolean next()
Moves to the next record in the GlideRecord.
boolean _next()
Provides the same functionality as next, intended to be used in cases where the GlideRecord has a column named next.
String operation()
Retrieves the current operation being performed, such as insert, update, delete, etc.
void orderBy(String name)
Specifies an orderBy column (this may be called more than once to order by multiple columns).
void orderByDesc(String name)
Specifies a decending orderBy column.
void query(Object field, Object value)
Runs the query against the table based on the specified filters 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.
void queryNoDomain(Object field, Object value)
Used only in domain separated instances. Performs the same function as query();, but turns off domain processing.
void _query(Object field, Object value)
Identical to query();, intended to be used on tables where there is a column named 'query, which would interfere with using query();.
void restoreLocation()
Sets the current record to be the record that was saved with saveLocation(). If saveLocation has not been called yet, the current record is set to be the first record of the GlideRecord.
void saveLocation()
Save the current row number so that we can get back to this location using restoreLocation().

3 Get

Get Method Summary
Return Value Details
boolean get(Object name, Object value)
Defines a GlideRecord based on the specified expression of 'name = value'. If value is not specified, then the expression used is 'sys_id = name'. This method is expected to be used to query for single records, so a 'next' operation on the GlideRecord is performed by this method before returning.
String getAttribute(String attribute)
Retrieves the attributes on the field in question from the dictionary.
String getClassDisplayValue()
Retrieves the label for the table.
String getDisplayValue()
Retrieves the display value for the current record.
ElementDescriptor getED()
Retrieves the element's descriptor.
GlideElement getElement(String columnName)
Retrieves the GlideElement for a specified field.
String getEncodedQuery()
Retrieves the encoded query as a string.
String getEscapedDisplayValue()
Retrieves the field value of the current record and escapes it for use in Jelly scripts.
ArrayList getFields()
Retrieves an array of fields in the current record.
String getLabel()
Retrieves the appropriate label for a field.
String getLink(boolean noStack)
Retrieves the link for the current record.
int getLocation()
Retrieves the current row number.
string getPlural()
Retrieves the plural label of the GlideRecord table.
String getRecordClassName()
Retrieves the class name for the current record.
HashMap getRelatedLists()
Retrieves a list of names and display values of tables that refer to the current record.
HashMap getRelatedTables()
Retrieves a list of names and display values of tables that are referred to by the current record.
int getRowCount()
Retrieves the number of rows in the GlideRecord.
int getRowNumber()
Retrieves the row number set by saveLocation() or setLocation().
String getTableName()
Retrieves the table name associated with this GlideRecord.
String getValue(String fieldName)
Retrieves the string value of an underlying element in a field.

4 Set

Set Method Summary
Return Value Details
void 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.

void setAbortAction(boolean b)
Sets a flag to indicate if the next database action (insert, update, delete) is to be aborted.
void setDisplayValue(String name, Object value)
Sets the field name to the specified display value.
  • For a reference field this is the display value for the table.
  • For a date/time field this is the time in the caller's current timezone.
void setForceUpdate(boolean e)
Updates the record even if fields have not been changed.
void setLimit(int limit)
Sets the limit for how many records in the GlideRecord.
void setLocation(int Number)
Sets the current row location.
void setNewGuid()
Generates a new GUID and sets it as the unique id for the current record.
void setNewGuidValue(String guid)
Generates a new GUID and sets it as the unique id for the current record, when inserting a new record.
void setQueryReferences(boolean queryReferences)
Enables or disables using the reference field's display name when querying a reference field.
void setUseEngines(boolean e)
Disable or enable the running of any engines (approval rules / assignment rules).
void setValue(String fieldName, Object value)
Sets the specified field to the specified value. Normally a script would do a gr.category = value. However, if the element name is a variable then gr.setValue(elementName, value) can be used.
return setWorkflow(boolean e)
Enables or disables the running of business rules that might normally be triggered by subsequent actions.

5 Update

Update Method Summary
Return Value Details
void applyTemplate(String template)
Apply a template record (from sys_templates) to the current record. If the specified template is not found, no action is taken.
string update(Object reason)
Updates the GlideRecord with any changes that have been made. If the record does not already exist, it is inserted.
string updateWithReferences(Object reason)
Updates a record and also inserts or updates any related records with the information provided.

6 Insert

Insert Method Summary
Return Value Details
void initialize()
Creates an empty record suitable for population before an insert.
string insert()
Insert a new record using the field values that have been set for the current record.
string insertWithReferences()
Inserts a new record and also inserts or updates any related records with the information provided.
void newRecord()
Creates a GlideRecord, set the default values for the fields and assign a unique id to the record.

See Also: initialize().

7 Delete

Delete Method Summary
Return Value Details
void deleteMultiple()
Delete multiple records according to the current "where" clause. Does not delete attachments.
boolean deleteRecord()
Delete a single record.



8 Query Methods

8.1 addActiveQuery

public QueryCondition addActiveQuery()

Adds a filter to return active records.
Returns:
QueryCondition - filter to return active records.
Example:
var inc = new GlideRecord('incident');
inc.addActiveQuery();
inc.query();




8.2 addEncodedQuery

public void addEncodedQuery(String query)

Adds an encoded query. Adds an encoded query to the other queries that may have been set.
Parameters:
query - An encoded query string to add to the record.
Example:
var queryString = "priority=1^ORpriority=2";
 var gr = new GlideRecord('incident');

 gr.addEncodedQuery(queryString);
 gr.query();
 while (gr.next()) {
   gs.addInfoMessage(gr.number);
 }

Use the breadcrumbs and filters to generate encoded query strings.


8.3 addDomainQuery

public void addDomainQuery(Object o)

Changes the domain used for the query from the user's domain to the domain of the provided GlideRecord.
Parameters:
o - A GlideRecord from which to draw the domain.
Example:
//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);
}



8.4 addInactiveQuery

public QueryCondition addInactiveQuery()

Adds a filter to return inactive records.
Returns:
QueryCondition - records where the active flag is false.
Example:
var inc = new GlideRecord('incident');
inc.addInactiveQuery();
inc.query();




8.5 addJoinQuery

public QueryCondition addJoinQuery(joinTable, [primaryField], [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).
Note: 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).
Parameters:
joinTable - table name.
primaryField (optional) - if other than sys_id, the primary field.
joinTableField (optional) - if other than sys_id, the field that joins the tables.
Returns:
QueryCondition - records where the relationships match.
Example:
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();


Example:
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'));
}


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




8.6 addNotNullQuery

public QueryCondition addNotNullQuery(String fieldName)

Adds a filter to return records where the specified field is not null.
Parameters:
fieldName - string name for a field.
Returns:
QueryCondition - QueryCondition of records where the parameter field is not null.
Example:
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
  }



8.7 addNullQuery

public QueryCondition addNullQuery(String fieldName)

Adds a filter to return records where the specified field is null.
Parameters:
fieldName - string name for a field.
Returns:
QueryCondition - QueryCondition of records where the parameter field is null.
Example:
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
  }



8.8 addOrCondition

public QueryCondition addOrCondition(String name, String oper, Object value)

Appends an OR condition to an existing condition based on the parameters entered. When using multiple query parameters, the addOrCondition method adds an OR condition to the last query.
Adds a disjunctive filter condition to return records based on 1, 2 or 3 arguments.
  • 1 argument adds an encoded query string.
  • 2 arguments return records where the field is equal to the value (or is in a list of values).
  • 3 arguments return records where the field meets the specified condition (field, operator and value).
Parameters:
name - string name of a field.
oper - an operator for the query.
value - value to query on.
Returns:
QueryCondition - a reference to the QueryCondition that was added to the GlideRecord.
Example:
var gr = new GlideRecord('incident');
var qc = gr.addQuery('category', 'hardware');
qc.addOrCondition('category', 'software');
gr.addQuery('priority', '1');



8.9 addQuery

public QueryCondition addQuery(String name, Object operator, Object value)

Adds a filter to return records based on 1, 2 or 3 arguments.
  • 1 argument adds an encoded query string.
  • 2 arguments return records where the field is equal to the value (or is in a list of values).
  • 3 arguments return records where the field meets the specified condition (field, operator and value).
Can accept an IN operator (see example 2).
Parameters:
name - string name of a field.
operator - an operator for the query.
value - value to query on.
Returns:
QueryCondition - a reference to the QueryCondition that was added to the GlideRecord.
Example 1:
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();
}


Example 2 - Using the IN Operator:
var que = new GlideRecord('incident');
que.addQuery('number','IN','INC00001,INC00002');
que.query();
while(que.next()) {
 //do something....
}


8.9.1 Controlling invalid queries

By default queries with invalid field names run but ignore the invalid condition. For more strict query control you can enable the glide.invalid_query.returns_no_rows property which will result in an empty result set for invalid queries.
When this property is enabled you can temporarily override this logic on the session by turning off strict query control.
gs.getSession().setStrictQuery(false);


Example:
/*
 * Default behavior if no property or property = false
 * Remove invalid query condition
 */
var gr = new GlideRecord("incident");
gr.addQuery("field_that_doesnt_exist", "my value");
gr.addQuery("active", true);
gr.query();
//returns records matching active=true

/*
 * Property = true
 * Invalidate entire query if invalid condition exists
 */
var gr = new GlideRecord("incident");
gr.addQuery("field_that_doesnt_exist", "my value");
gr.addQuery("active", true);
gr.query();
// returns no records
//also generated log message "field name 'field_that_doesnt_exist' not found in table 'incident'"


/*
 * Property = true, override strict query for session
 * Same behavior as setting property = false except only applies to this session
 */
//disable strict query
gs.getSession().setStrictQuery(false);

var gr = new GlideRecord("incident");
gr.addQuery("field_that_doesnt_exist", "my value");
gr.addQuery("active", true);
gr.query();
//returns records matching active=true

//restore strict query
gs.getSession().setStrictQuery(true);

8.10 canCreate

public boolean canCreate()

Determines if the Access Control Rules (which includes the user's role) permit inserting new records in this table.
Returns:
boolean - true if the user's role permits creation of new records in this file.

8.11 canDelete

public boolean canDelete()

Determines if the Access Control Rules (which includes the user's role) permit deletion of records in this table.
Returns:
boolean - true if can delete or false if cannot delete.
Example:
Note
Note: This API call changed in the Calgary release:
  • GlideSecurityManager replaces Packages.com.glide.sys.security.GlideSecurityManager

The new script object calls apply to the Calgary release and beyond. For releases prior to Calgary, substitute the packages call as described above. Packages calls are not valid beginning with the Calgary release. For more information, see Scripting API Changes.

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



8.12 canRead

public boolean canRead()

Determines if the Access Control Rules (which includes the user's role) permit reading this table.
Returns:
boolean - true if can read or false if cannot read.

8.13 canWrite

public boolean canWrite()

Determines if the Access Control Rules (which includes the user's role) permit updates to records in this table.
Returns:
boolean - true if can write or false if cannot write to the table.

8.14 changes

public boolean changes()

Determines whether any of the fields in the record have changed.
Returns:
boolean - true if any of the fields in the record have changed.

8.15 find

public boolean find(columnName, 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.
Parameters:
columnName - specifies the column name in a record.
value - specifies the value to check for in the specified column.
Returns:
boolean - true if any record has a matching value in the specified column.

8.16 hasAttachments

public boolean hasAttachments()

Determines if the current record has any attachments.
Returns:
boolean - true if the current record has attachments.
Example:
  //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();
    }    
  }



8.17 hasNext

public boolean hasNext()

Determines if there are any more records in the GlideRecord.
Parameters:
boolean - true if there are more records in the query set.
Example:
if (gr.hasNext()) {
  dothis(); // found it, do it
} else {
  dothat(); // didn't find it
}
;



8.18 instanceOf

public boolean instanceOf(String className)

Checks a table for a type/class of record.
Parameters:
className - A string name of a type or class of record.
Returns:
boolean - true if table is instance of specified class.
Example:

8.19 isNewRecord

public boolean 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.
Returns:
boolean - true if the current record is new (not inserted into the database).
Example:
Example of scripted ACL:
answer = gs.hasRole("filter_admin") || current.isNewRecord()

Example UI action condition:

*** Script: true
*** Script: false

8.20 isValid

public boolean isValid()

Determines whether the table exists or not.
Returns:
boolean - true if table is valid or if record was successfully fetched, or false if table is invalid or record was not successfully fetched.
Example:
var testTable = new GlideRecord('incident');
gs.print(testTable.isValid());

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

Output:

*** Script: true
*** Script: false



8.21 isValidField

public boolean isValidField(String columnName)

Determines if the given field is defined in the current table.
Parameters:
columnName - column name of a field as a string.
Returns:
boolean - true if field is valid.

8.22 isValidRecord

public boolean isValidRecord()

Determine if there is another record in the GlideRecord.
Returns:
boolean - true if the current record is valid or false if past the end of the recordset.

8.23 next

public boolean next()

Moves to the next record in the GlideRecord.
Returns:
boolean - false if there are no more records in the query set .
Example:
var rec = new GlideRecord('incident');
rec.query();
while (rec.next()) { 
  gs.print(rec.number + ' exists');
}


8.24 _next

public boolean _next()

Provides the same functionality as next, intended to be used in cases where the GlideRecord has a column

named next.

Moves to the next record in the GlideRecord.
Returns:
boolean - false if there are no more records in the query set .
Example:
var rec = new GlideRecord('sys_template');
rec.query();
while (rec._next()) { 
  gs.print(rec.number + ' exists');
}



8.25 operation

public String operation()

Retrieves the current operation being performed, such as insert, update, delete, etc.
Returns:
String - the current operation.

8.26 orderBy

public void orderBy(String name)

Specifies an orderBy column (this may be called more than once to order by multiple columns).
Parameters:
name - a column name used to order the recordset.
Example:
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');
}



8.27 orderByDesc

public void orderByDesc(String name)

Specifies a decending orderBy column.
Parameters:
name - a column name used to order the GlideRecord.

8.28 query

public void 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.
Parameters:
name - a column name to query on.
value - a value to query for.
Example:
var rec = new GlideRecord('incident');
rec.query();
while (rec.next()) { 
 gs.print(rec.number + ' exists');
}



8.29 queryNoDomain

public void query(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.
Parameters:
name - a column name to query on.
value - a value to query for.
Example:
var rec = new GlideRecord('incident');
rec.queryNoDomain();
while (rec.next()) { 
 gs.print(rec.number + ' exists');
}



8.30 _query

public void _query(Object field, Object value)

Identical to query();, intended to be used on tables where there is a column named 'query, which would interfere with using query();.
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.
Parameters:
name - a column name to query on.
value - a value to query for.
Example:
var rec = new GlideRecord('sys_app_module');
rec._query();
while (rec.next()) { 
 gs.print(rec.number + ' exists');
}



8.31 restoreLocation

public void restoreLocation(boolean b)

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

8.32 saveLocation

public void saveLocation()

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



9 Get Methods

9.1 get

public boolean get(Object name, Object value)

Defines a GlideRecord based on the specified expression of 'name = value'. If value is not specified, then the expression used is 'sys_id = name'. This method is expected to be used to query for single records, so a 'next' operation on the recordset is performed by this method before returning.
Parameters:
name - column name.
value - (optional) value to match.
Returns:
name - true if a matching record(s) was found or false if no matches found.
Example:
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;
 }



9.2 getAttribute

Gets the attributes on the field in question from the dictionary.

public String getAttribute(String)

Retrieves the attributes on the field in question from the dictionary.
Parameters:
String - the column name as a string to get the attributes from.
Returns:
String - the attribute values as a string.
Example:
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"));
  }
}



9.3 getClassDisplayValue

public String getClassDisplayValue()

Retrieves the label for the table.
Returns:
String - label that describes the table.

9.4 getDisplayValue

public String getDisplayValue()

Retrieves the display value for the current record.
Returns:
String - a string display value for the current record.
Example:
// 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]);
  }



9.5 getED

public ElementDescriptor getED()

Retrieves the element's descriptor.
Returns:
ElementDescriptor - the current element's descriptor.
Example:
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;



9.6 getElement

public GlideElement getElement(String columnName)

Retrieves the GlideElement for a specified field.
Parameters:
columnName - a column name to get the element from.
Returns:
GlideElement - a GlideElement.

9.7 getEncodedQuery

public String getEncodedQuery(boolean b)

Retrieves the encoded query as a string.
Parameters:
String - Gets the encoded query as a string.

9.8 getEscapedDisplayValue

public String getEscapedDisplayValue()

Retrieves the field value for the display field of the current record and escape it for use in Jelly scripts.
Returns:
String - escaped value of display column.

9.9 getFields

public ArrayList getFields()

Retrieves a Java ArrayList of fields in the current record.
Parameters:
ArrayList - a Java ArrayList of fields in the current record.
Example:
// 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);
  }
}



9.10 getLabel

public String getLabel()

Retrieves the appropriate label for a field.
Returns:
String - the label of the field as a string.
Example:
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");  
      }
    }
}



9.11 getLink

public String getLink(boolean noStack)

Retrieves the link for the current record.
Parameters:
noStack - if true, the link generated will not append &sysparm_stack=[tablename]_list.do?sysparm_query=active=true to the end of the URL; if false, the link will. Leaving the argument empty will default to false.
Returns:
String - a URL.
Example:
  //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();
    }   
  }



9.12 getLocation

public int getLocation(boolean b)

Retrieves the current row number.
Returns:
int - Returns the row number of the current record.

9.13 getPlural

public string getPlural()

Retrieves the plural label of the GlideRecord table.
Returns:
string - the plural label of the GlideRecord's table.
For example, if the table name is "Change Request," this method would return "Change Requests."

9.14 getRecordClassName

public String getRecordClassName()

Retrieves the class name for the current record.
Parameters:
String - class or table name.
Example:
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;
}


9.15 getRelatedLists

public HashMap getRelatedLists(boolean b)

Retrieves a list of names and display values of tables that refer to the current record.
Returns:
HashMap - hashmap with names and display values of related tables.

9.16 getRelatedTables

public HashMap getRelatedTables(boolean b)

Retrieves a list of names and display values of tables that arereferred to by the current record.
Parameters:
HashMap - hashmap with names and display values of related tables.

9.17 getRowCount

public int getRowCount()

Retrieves the number of rows in the GlideRecord.
Returns:
int - an integer count of rows.
Example:
var gr = new GlideRecord('incident')
gr.query();
gs.info("Records in incident table: " + gr.getRowCount());



9.18 getRowNumber

public int getRowNumber()

Retrieves the row number set by saveLocation() or setLocation(). To get the current row, use getLocation() instead.
Returns:
int - the saved row number.

9.19 getTableName

public String getTableName()

Retrieves the table name associated with this GlideRecord.
Returns:
String - table name.
Example:
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);}
}



9.20 getValue

public String getValue(String fieldName)

Retrieves the string value of an underlying element in a field.
Parameters:
fieldName - the name of the field from which to get the value.
Returns:
String - the string value of the underlying element. Returns null if the field is empty, or the field does not exist.



10 Set Methods

10.1 autoSysFields

public void autoSysFields(boolean e)

Note
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.


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: 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.
Parameters:
e - Boolean variable that if false disables updates to sys_updated_by, sys_updated_on, sys_mod_count, sys_created_by, and sys_created_on.
Example:
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();
}



10.2 setAbortAction

public void setAbortAction(boolean b)

Sets a flag to indicate if the next database action (insert, update, delete) is to be aborted.
Parameters:
b - true to abort next action or false if action is to be allowed.
Example:
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);
  }
}



10.3 setDisplayValue

public void setDisplayValue(String name, Object value)

Sets the field name 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.
Parameters:
name - String value of the field name.
value - Display value to set for the field.
Example:
var gr = new GlideRecord('incident');
gr.get('46f09e75a9fe198100f4ffd8d366d17b');
gr.setDisplayValue('opened_at','2011-02-13 4:30:00');
gr.update();



10.4 setForceUpdate

public void setForceUpdate(boolean force)

Updates the record even if fields have not been changed.
Parameters:
force - true to update even if fields have not changed, otherwise false.

10.5 setLimit

public void setLimit(int)

Sets the limit for how many records are in the GlideRecord.
Parameters:
int - Integer limit for records to fetch.
Example:
var gr = new GlideRecord('incident');
gr.orderByDesc('sys_created_on');
gr.setLimit(10);
gr.query();



10.6 setLocation

public void setLocation(int rowNumber)

Sets the current row location.
Parameters:
rowNumber - integer that is the number of the row to set as the current row.

10.7 setNewGuid

public void 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.
Example:
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();



10.8 setNewGuidValue

public void setNewGuidValue(String guid)

Generates a new GUID and sets it as the unique id for the current record, when inserting a new record.
Parameters:
guid - a string value for the new GUID.

10.9 setQueryReferences

public void setQueryReferences(boolean queryReferences)

Enables or disables using the reference field's display name when querying a reference field.
Parameters:
queryReferences - Boolean variable. If set to true, will generate a string of display names; if false, will generate a string of sys_ids.

10.10 setUseEngines

public void setUseEngines(boolean e)

Disable or enable the running of any engines (approval rules / assignment rules).
Parameters:
e - if true enables engines, and if false disables engines.

10.11 setValue

public void 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.
Parameters:
name - a field name.
value - an object value.



10.12 setWorkflow

public void 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.
Parameters:
e - Boolean variable that if true (default) enables business rules, and if false to disables them.
Example:
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');
      }
    }
  }
}
Note:setWorkflow() is ignored when subsequently using either deleteProblem() or deleteMultiple() to cascade delete.

11 Update Methods

11.1 applyTemplate

public void 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.
Parameters:
template - Takes a name of a template on the sys_template table.
Example:
var rec1 = new GlideRecord("incident");
rec1.initialize();
rec1.applyTemplate("my_incident_template");

//...possibly more code here... 
rec1.insert();



11.2 update

public string update(Object reason)

Updates the GlideRecord with any changes that have been made. If the record does not already exist, it is inserted.
Parameters:
reason - Takes a string designating the reason for the update if necessary. The reason will be displayed in the audit record.
Returns:
String - unique id of new or updated record.
Example:
  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();
   }
}



11.3 updateWithReferences

public string updateWithReferences(Object reason)

Updates a record and also inserts or updates any related records with the information provided.
Returns:
string - unique ID for the record being updated.
Parameters:
reason - takes a string designating the reason for the update if necessary. The reason will be displayed in the audit record.
Example
  • if processing a 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 a 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();
}



12 Insert Methods

12.1 initialize

Creates an empty record suitable for population before an insert.

public void initialize()

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



12.2 insert

public string insert()

Inserts a new record using the field values that have been set for the current record.
Returns:
string - unique id of the inserted record or null if record is not inserted.
Example:
var gr = new GlideRecord('to_do');
gr.initialize(); 
gr.name = 'first to do item'; 
gr.description = 'learn about GlideRecord'; 
gr.insert();



12.3 insertWithReferences

public string insertWithReferences()

Inserts a new record and also inserts or updates any related records with the information provided.
Returns:
string - unique ID for the record being inserted.
Example
If a reference value is not specified (as below), then a new user record will be 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();
}


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



12.4 newRecord

public void newRecord()

Creates a GlideRecord, set the default values for the fields and assign a unique id to the record. See Also: initialize().

13 Delete Methods

13.1 deleteMultiple

public void deleteMultiple()

Deletes multiple records according to the current "where" clause. Does not delete attachments.
Example:
  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();
Note: Dot-walking is not supported for this method. When deploying the deleteMultiple() function on referenced tables, all the records in the table will be deleted. Also, when using deleteRecord() to cascade delete, prior calls to setWorkflow() on the same GlideRecord object are ignored.

13.2 deleteRecord

public boolean deleteRecord()

Deletes a single record.
Parameters:
boolean - true if record was deleted or false if none found to delete.
Example:
var gr = new GlideRecord('incident')
gr.addQuery('sys_id','99ebb4156fa831005be8883e6b3ee4b9'); //to delete one record
gr.query();
gr.next();
gr.deleteRecord();
}
Note:When using deleteMultiple() to cascade delete, prior calls to setWorkflow() on the same GlideRecord object are ignored.
Was this article helpful?
Yes, I found what I needed
No, I need more assistance