Loading

GlideSystem

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


1 Overview

The GlideSystem (referred to by the variable name 'gs' in Business Rules) provides a number of convenient methods to get information about the system, the current logged in user, etc. For example, the method addInfoMessage() permits communication with the user.

 gs.addInfoMessage('Email address added for notification');

Many of the GlideSystem methods facilitate the easy inclusion of dates in query ranges and are most often used in filters and reporting.

The Method Detail is in three sections:

  • General functions
  • Date and Time functions
  • User Session functions

2 Method Summary

General

Method Summary Description
eventQueue(String, Object, String, String, String) Queues an event for the event manager.
getDisplayColumn(String) Gets the display column for the table.
getDisplayValueFor(String, String, String) Gets the display value for a given field.
getEscapedProperty(String, Object) Gets the property and escapes it for XML parsing.
getMessage(String, Object) Retrieves a message from UI messages.
getMessageS(String, Object) Retrieves a message from UI messages and escapes all ticks (').
getNodeValue(object, Integer) Gets the node value for specified index.
getNodeName(Object, Integer) Returns the node name for specified index.
getProperty(String, Object) Gets the value of a Glide property.
getScriptError(String) Returns the script error found in the specified script, if there is one. The script is not executed by this function, only checked for syntax errors.
getStyle(String, String, String) Returns the style defined for the table, field and value.
getXMLText (String, String) Gets the xml text for the first node in the xml string that matches the path query.
getXMLNodeList(String) Constructs an Array of all the nodes and values in an XML document.
log(String message, String source) Logs a message to the system log and saves it to the syslog table.
logError(String message, String source) Logs an error to the system log and saves it to the syslog table.
logWarning(String message, String source) Logs a warning to the system log and saves it to the syslog table.
nil(Object) Queries an object and returns true if the object is null or contains an empty string.
print(String) Writes a message to the system log. This method does not write the message to the syslog table unless debug has been activated.
tableExists(String) Determines if a database table exists.
workflowFlush(Object) Deletes all existing workflow operations for the specified GlideRecord.

Date and Time Functions

Method Summary Description
beginningOfLastMonth() Gets the date and time for the beginning of last month in GMT.
beginningOfLastWeek() Gets the date and time for the beginning of last week in GMT.
beginningOfNextWeek() Gets the date and time for the beginning of next week in GMT.
beginningOfNextMonth() Gets the date and time for the beginning of next month in GMT.
beginningOfNextYear() Gets the date and time for the beginning of next year in GMT.
beginningOfThisMonth() Gets the date and time for the beginning of this month in GMT.
beginningOfThisQuarter() Gets the date and time for the beginning of this quarter in GMT.
beginningOfThisWeek() Gets the date and time for the beginning of this week in GMT.
beginningOfThisYear() Gets the date and time for the beginning of this week in GMT.
beginningOfToday() Gets the date and time for the beginning of today in GMT.
beginningOfYesterday() Gets the date and time for the beginning of yesterday in GMT.
calDateDiff(String, String, boolean) Calculate the difference between two dates using the default calendar. Note: Calendars are now legacy. If Schedules are being used, see Calculate Duration Given a Schedule.
dateDiff(String, String, boolean) Calculates the difference between two dates.
dateGenerate(String, String) Generates a date and time for the specified date.
daysAgo(int) Gets a date and time for a certain number of days ago.
daysAgoEnd(int) Gets a date and time for end of the day a certain number of days ago.
daysAgoStart(int) Gets a date and time for beginning of the day a certain number of days ago.
endOfLastMonth() Gets the date and time for the end of last month in GMT.
endOfLastWeek() Gets the date and time for the end of last week in GMT, in the format yyyy-mm-dd hh:mm:ss.
endOfLastYear() Gets the date and time for the end of last year in GMT.
endOfNextMonth() Gets the date and time for the end of next month in GMT.
endOfNextWeek() Gets the date and time for the end of next week in GMT.
endOfNextYear() Gets the date and time for the end of next year in GMT.
endOfThisMonth() Gets the date and time for the end of this month in GMT.
endOfThisQuarter() Gets the date and time for the end of this quarter in GMT.
endOfThisWeek() Gets the date and time for the beginning of this week in GMT.
endOfThisYear() Gets the date and time for the end of this year in GMT.
endOfToday() Gets the date and time for the end of today in GMT.
endOfYesterday() Gets the date and time for the end of yesterday in GMT.
hoursAgo(int) Gets a date and time for a certain number of hours ago.
hoursAgoEnd(int) Gets a date and time for the end of the hour a certain number of hours ago.
hoursAgoStart(int) Gets a date and time for the start of the hour a certain number of hours ago.
lastWeek() Date and time one week ago in GMT.
minutesAgo(int) Gets a date and time for a certain number of minutes ago.
minutesAgoEnd(int) Gets a date and time for the end of the minute a certain number of minutes ago.
minutesAgoStart(int) Gets a date and time for a certain number of minutes ago.
monthsAgo(int) Gets a date and time for a certain number of months ago.
monthsAgoEnd(int) Gets a date and time for the last day of the month a certain number of months ago.
monthsAgoStart(int) Gets a date and time for the first day of the month a certain number of months ago.
now() Gets the current date.
nowNoTZ() Gets the current GMT date time.
nowDateTime() Gets the current date and time.
quartersAgo(int) Gets a date and time for a certain number of quarters ago.
quartersAgoEnd(int) Gets a date and time for the last day of the quarter a certain number of quarters ago.
quartersAgoStart(int) Gets a date and time for the first day of the quarter a certain number of quarters ago.
yearsAgo(int) Gets a date and time for a certain number of years ago.
yesterday() Gets yesterday's time.
isFirstDayOfMonth(Object)

Checks whether the date is the first day of the month.

isFirstDayOfWeek(Object)

Checks whether the date is the first day of the week. This uses the ISO standard of Monday being the first day of the week.

isFirstDayOfYear(Object)

Checks whether the date is the first day of the year

isLastDayOfMonth(Object)

Checks whether the date is the last day of the month.

isLastDayOfWeek(Object)

Checks whether the date is the last day of the week.

isLastDayOfYear(Object)

Checks whether the date is the last day of the year.

User Session Functions

Method Summary Description
addErrorMessage(Object) Adds an error message for the current session. Can be accessed using getErrorMessages().
addInfoMessage(Object) Adds an info message for the current session. Can be called using getInfoMessages().
addMessage(String, Object) Adds a message for the current session. Can be called using getMessages(String).
clearClientData(String) Clears a specified session client name/value pair previously set with putClientData().
flushMessages() Clears any session messages saved using addErrorMessage(Object) or addInfoMessage(Object).
getClientData(String) Gets a session client value previously set with putClientData().
getErrorMessages() Get the list of error messages for the session that were added by addErrorMessage(Object).
getImpersonatingUserDisplayName() Return the display name of the impersonating user.
getImpersonatingUserName() Return the name of the impersonating user or null if not impersonating.
getInfoMessages() Get the list of info messages for the session that were added via addInfoMessage(Object.
getMessages(String) Get the list of messages of the specified type for the session that were added via addMessage(String, Object).
getPreference(String, Object) Gets a user preference.
getRoles() Gets a list of roles for the current user.
getSession() Gets a reference to the current Glide session.
getSessionID() Accesses the GlideSession Session ID.
getTrivialMessages() Get the list of error messages for the session that were added with the trivial flag.
getUser() Return a reference to the User object for the current user. More information is available here.
getUserDisplayName() Return the name field of the current user (e.g. John Smith, as opposed to jsmith).
getUserID() Return the sys_id of the current user.
getUserName() Return the username of the current user (for example, jsmith).
getUserNameByUserID(String) Gets the username based on a user ID.
hasRole(String) Determine if the current user has the specified role.
hasRoleInGroup(Object, Object) Determine if the current user has the specified role within a specified group.
isInteractive() Check if the current session is interactive.
isLoggedIn() Determine if the current user is currently logged in.
putClientData(String, String) Sets a name/value pair that is associated with the current session and made available on the client for use in client scripts.
setRedirect(Object) Set the redirect URI for this transaction. This determines the next page the user will see.
setReturn(Object) Sets the return URI for this transaction. This determines what page the user will be directed to when they return from the next form.
userID() Returns the sys_id of the user associated with this session. A shortcut for the more proper getUserID().

3 General

3.1 eventQueue(String, Object, String, String, String)

Queues an event for the event manager.

3.1.1 Input Fields

Parameters:

  • Name of the event being queued.
  • A GlideRecord object, such as "current".
  • An optional parameter, saved with the instance if specified.
  • A second optional parameter, saved with the instance if specified.
  • An event queue to add the event to.

3.1.2 Example

if (current.operation() != ‘insert’ && current.comments.changes()) {
    gs.eventQueue(“incident.commented, current, gs.getUserID(), gs.getUserName());
}

3.2 getDisplayColumn(String)

Gets the display column for the table.

3.2.1 Input Fields

Parameters: name of table from which to get the display column name.

3.2.2 Output Fields

Returns: name of the display column for the table.

3.2.3 Example

// Return the sys_id value for a given table and its display value
function GetIDValue(table, displayValue) { 
    var rec = new GlideRecord(table);
    var dn = gs.getDisplayColumn(table);
    if (rec.get(dn, displayValue))
        return rec.sys_id;
    else
        return null;
}

3.3 getDisplayValueFor(String, String, String)

Gets the display value for a specified field on a record.

3.3.1 Input Fields

Parameters:

  • String - name of table for the record
  • String - the sysid for the record to get the display value from
  • String - the field to get a display value from

3.3.2 Output Fields

Returns: name of the display value for the field's value.

3.4 getEscapedProperty(String, Object)

Gets the property and escapes it for XML parsing.

3.4.1 Input Fields

Parameters:

  • String key for the property whose value should be returned
  • Alternate object to return if the property is not found.

3.4.2 Output Fields

Returns: the property as a string, or the alternate object specified above.

3.5 getMessage(String, Object)

Retrieves a message from UI messages. Note: if the UI message has a tick ('), there may be issues with the message in the script; to escape the ticks ('), use getMessageS(String, Object).

3.5.1 Input Fields

Parameters:

  • ID of message
  • (Optional) A list of strings or other values defined by java.text.MessageFormat, which allows you to produce language-neutral messages for display to users.

3.5.2 Output Fields

Returns: the UI message as a string.

3.5.3 Example

var my_message = '${gs.getMessage("This is a message.")}'; 
alert(my_message);

3.6 getMessageS(String, Object)

Retrieves a message from UI messages and escapes all ticks ('). Useful if you are inserting into a JavaScript expression from Jelly.

For instance, the following code snippet will fail if the returned snippet has a tick ('):

var my_message = '${gs.getMessage("I love France")}'; 
alert(my_message);

The solution is to use a snippet like the following:

var my_message = '${gs.getMessageS("I love France")}'; 
alert(my_message);

3.6.1 Input Fields

Parameters:

  • ID of message
  • Optional message arguments.

3.6.2 Output Fields

Returns: the message as a string, with the ticks escaped.

3.6.3 Example

var my_message = '${gs.getMessageS("I love France")}'; 
alert(my_message);

3.7 getProperty(String, Object)

Gets the value of a Glide property. If the property is not found, return an alternate value. Use getEscapedProperty(String, Object) to escape the property.

3.7.1 Input Fields

Parameters:

  • String key for the property whose value should be returned.
  • Alternate object to return if the property is not found.

3.7.2 Output Fields

Returns: (String) the value of the Glide property, or the alternate object defined above.

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

3.8 getScriptError(String)

Returns the script error found in the specified script, if there is one. The script is not executed by this function, only checked for syntax errors.

3.8.1 Input Fields

Parameters: string script to check for errors.

3.8.2 Output Fields

Returns: the script error message or, if none, then null.

3.9 getStyle(String, String, String)

Returns the style defined for the table, field and value.

3.9.1 Input Fields

Parameters:

  • Table name
  • Field name
  • Field value

3.9.2 Output Fields

Returns the style as a string.

3.10 log(String message, String source)

Logs a message to the system log and saves it to the syslog table.

3.10.1 Input Fields

Parameters:

  • String message - message to log, for the log's Message field.
  • String source - (optional) the source of the message, for the log's Source field.

3.10.2 Example

var count = new GlideAggregate('incident');
count.addQuery('active', 'true');
count.addAggregate('COUNT', 'category');
count.query();   
while (count.next()) {
   var category = count.category;
   var categoryCount = count.getAggregate('COUNT', 'category');
   gs.log("The are currently " + categoryCount + " incidents with a category of " + category, "Incident Counter");
}

3.11 logError(String message, String source)

Logs an error to the system log and saves it to the syslog table.

3.11.1 Input Fields

Parameters:

  • String message - message to log, for the log's Message field.
  • String source - (optional) the source of the message, for the log's Source field.

3.12 logWarning(String message, String source)

Logs a warning to the system log and saves it to the syslog table.

3.12.1 Input Fields

Parameters:

  • String message - message to log, for the log's Message field.
  • String source - (optional) the source of the message, for the log's Source field.

3.13 nil(Object)

Queries an object and returns true if the object is null or contains an empty string.

3.13.1 Input Fields

Parameters: name of an object

3.13.2 Output Fields

Returns: true if null or empty string; otherwise, returns false

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

3.14 print(String)

Writes a message to the system log. This method does not write the message to the syslog table unless debug has been activated.

3.14.1 Input Fields

Parameters: message to log

3.14.2 Example

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

3.15 tableExists(String)

Determines if a database table exists.

3.15.1 Input Fields

Parameters: name of table to check for existence

3.15.2 Output Fields

Returns: true if table exists or false is not found

3.16 workflowFlush(Object)

Deletes all existing workflow operations for the specified GlideRecord.

3.16.1 Input Fields

Parameters: the GlideRecord to flush the workflow for

3.16.2 Output Fields

Returns: void


4 Date/Time

4.1 beginningOfLastMonth()

Gets the date and time for the beginning of last month in GMT.

4.1.1 Output Fields

Returns: the GMT beginning of last month, in the format yyyy-mm-dd hh:mm:ss.

4.2 beginningOfLastWeek()

Gets the date and time for the beginning of last week in GMT.

4.2.1 Output Fields

Returns: the GMT beginning of last week, in the format yyyy-mm-dd hh:mm:ss.

4.3 beginningOfNextWeek()

Gets the date and time for the beginning of next week in GMT.

4.3.1 Output Fields

Returns: the GMT beginning of next week, in the format yyyy-mm-dd hh:mm:ss.

4.4 beginningOfNextMonth()

Gets the date and time for the beginning of next month in GMT.

4.4.1 Output Fields

Returns: the GMT beginning of next month, in the format yyyy-mm-dd hh:mm:ss.

4.5 beginningOfNextYear()

Gets the date and time for the beginning of next year in GMT.

4.5.1 Output Fields

Returns: the GMT beginning of next year, in the format yyyy-mm-dd hh:mm:ss.

4.6 beginningOfThisMonth()

Gets the date and time for the beginning of this month in GMT.

4.6.1 Output Fields

Returns: the GMT beginning of this month, in the format yyyy-mm-dd hh:mm:ss.

4.7 beginningOfThisQuarter()

Gets the date and time for the beginning of this quarter in GMT.

4.7.1 Output Fields

Returns: the GMT beginning of this quarter, in the format yyyy-mm-dd hh:mm:ss.

4.8 beginningOfThisWeek()

Gets the date and time for the beginning of this week in GMT.

4.8.1 Output Fields

Returns: the GMT beginning of this week, in the format yyyy-mm-dd hh:mm:ss.

4.9 beginningOfThisYear()

Gets the date and time for the beginning of this week in GMT.

4.9.1 Output Fields

Returns: the GMT beginning of this week, in the format yyyy-mm-dd hh:mm:ss.

4.10 beginningOfToday()

Gets the date and time for the beginning of today in GMT.

4.10.1 Output Fields

Returns: the GMT beginning of today, in the format yyyy-mm-dd hh:mm:ss.

4.11 beginningOfYesterday()

Gets the date and time for the beginning of yesterday in GMT.

4.11.1 Output Fields

Returns: the GMT beginning of yesterday, in the format yyyy-mm-dd hh:mm:ss.

4.12 calDateDiff(String, String, boolean)

Calculate the difference between two dates using the default calendar. Note: Calendars are now legacy. If Schedules are being used, see Calculate Duration Given a Schedule.

4.12.1 Input Fields

Parameters:

  • startDate - a starting date to compare, in the current users date format
  • endDate - an ending date to compare, in the current users date format
  • boolean numericValue - if true, the return will be formatted in number of seconds; if false, the return will be formatted ddd hh:mm:ss.

4.12.2 Output Fields

Returns: if the numericValue boolean parameter is true, returns the difference between the two dates as an integer number of seconds; if false, returns the difference between the two dates in the format ddd hh:mm:ss.

4.13 dateDiff(String, String, boolean)

Calculates the difference between two dates. This method expects the earlier date as the first parameter and the later date as the second parameter; otherwise, the method returns the difference as a negative value. Note: Use getDisplayValue() to convert the strings to the expected format.

4.13.1 Input Fields

Parameters:

  • startDate - a starting date to compare, in the current user's date format.
  • endDate - an ending date to compare, in the current user's date format.
  • boolean bnumericValue - true to return difference in number of seconds as a string, false to return difference in the format ddd hh:mm:ss.

4.13.2 Output Fields

Returns: if boolean bnumericValue is true, the difference in number of seconds; if false, the difference in the format ddd hh:mm:ss.

4.13.3 Example

For more examples, see Setting the Duration Field Value.

// Given two date/times as DateTime objects
// Set the values this way to ensure a consistent input time
var date1 = new GlideDateTime();
var date2 = new GlideDateTime();
date1.setDisplayValueInternal('2014-01-01 12:00:00');
date2.setDisplayValueInternal('2014-01-01 13:00:00');
 
// Determine the difference as number of seconds (returns a string)
// Use getDisplayValue() to convert the string to the format expected by dateDiff()
var diffSeconds = gs.dateDiff(date1.getDisplayValue(), date2.getDisplayValue(), true);
 
// JavaScript will coerce diffSeconds from a string to a number
// since diffSeconds is being compared to a number
var msg = (diffSeconds <= 0) ? ' is on or after ' : ' is before ';
gs.print(date1.getDisplayValue() + msg + date2.getDisplayValue())

4.14 dateGenerate(String, String)

Generates a date and time for the specified date.

4.14.1 Input Fields

Parameters:

  • Date - format: yyyy-mm-dd
  • Range - start, end, or a time in the 24 hour format hh:mm:ss.

4.14.2 Output Fields

Returns: a date and time in the format yyyy-mm-dd hh:mm:ss. If range is start, the returned value is yyyy-mm-dd 00:00:00; If range is end the return value is yyyy-mm-dd 23:59:59.

4.15 daysAgo(int)

Gets a date and time for a certain number of days ago.

4.15.1 Input Fields

Parameters: An integer number of days ago.

4.15.2 Output Fields

Returns: The (GMT) beginning of the days that was the specified number of days ago, in the format yyyy-mm-dd hh:mm:ss.

4.15.3 Example

function contractNoticeDue() {
    var gr = new GlideRecord("contract");
    gr.addQuery("u_contract_status", "Active");
    gr.query();
    while (gr.next()) {
        if ((gr.u_termination_date <= gs.daysAgo(-90)) && (gr.u_contract_duration == "Long")) {
            gr.u_contract_status = "In review";
        } 
        else if ((gr.u_termination_date <= gs.daysAgo(-50)) && (gr.u_contract_duration == "Medium")) {
            gr.u_contract_status = "In review";
        } 
        else if ((gr.u_termination_date <= gs.daysAgo(-10)) && (gr.u_contract_duration == "Short")) {
            gr.u_contract_status = "In review";
        }
    }
    gr.update();
}

4.16 daysAgoEnd(int)

Gets a date and time for end of the day a certain number of days ago.

4.16.1 Input Fields

Parameters: An integer number of days ago.

4.16.2 Output Fields

Returns: The (GMT) end of the day that was the specified number of days ago, in the format yyyy-mm-dd hh:mm:ss.

4.17 daysAgoStart(int)

Gets a date and time for beginning of the day a certain number of days ago.

4.17.1 Input Fields

Parameters: An integer number of days ago.

4.17.2 Output Fields

Returns: The (GMT) start of the day that was the specified number of days ago, in the format yyyy-mm-dd hh:mm:ss.

4.17.3 Example

var gr = new GlideRecord('sysapproval_approver');
gr.addQuery('state', 'requested');
gr.addQuery('sys_updated_on', '<', gs.daysAgoStart(5));
gr.query();
while(gr.next()){
  gs.eventQueue("approval.requested.idle", gr, gs.getUserID(),gs.getUserName());
}

4.18 endOfLastMonth()

Gets the date and time for the end of last month in GMT.

4.18.1 Output Fields

Returns: the GMT end of last month, in the format yyyy-mm-dd hh:mm:ss.

4.19 endOfLastWeek()

Gets the date and time for the end of last week in GMT, in the format yyyy-mm-dd hh:mm:ss.

4.19.1 Output Fields

Returns: the GMT end of last week, in the format yyyy-mm-dd hh:mm:ss.

4.20 endOfLastYear()

Gets the date and time for the end of last year in GMT.

4.20.1 Output Fields

Returns: the GMT end of last year, in the format yyyy-mm-dd hh:mm:ss.

4.21 endOfNextMonth()

Gets the date and time for the end of next month in GMT.

4.21.1 Output Fields

Returns: the GMT end of next month, in the format yyyy-mm-dd hh:mm:ss.

4.22 endOfNextWeek()

Gets the date and time for the end of next week in GMT.

4.22.1 Output Fields

Returns: the GMT end of next week, in the format yyyy-mm-dd hh:mm:ss.

4.23 endOfNextYear()

Gets the date and time for the end of next year in GMT.

4.23.1 Output Fields

Returns: the GMT end of next year, in the format yyyy-mm-dd hh:mm:ss.

4.24 endOfThisMonth()

Gets the date and time for the end of this month in GMT.

4.24.1 Output Fields

Returns: the GMT end of this month, in the format (yyyy-mm-dd huh:mm:ss)

4.25 endOfThisQuarter()

Gets the date and time for the end of this quarter in GMT.

4.25.1 Output Fields

Returns: the GMT end of this quarter, in the format yyyy-mm-dd hh:mm:ss.

4.26 endOfThisWeek()

Gets the date and time for the beginning of this week in GMT.

4.26.1 Output Fields

Returns: the GMT beginning of this week, in the format yyyy-mm-dd hh:mm:ss.

4.27 endOfThisYear()

Gets the date and time for the end of this year in GMT.

4.27.1 Output Fields

Returns: the GMT end of this year, in the format yyyy-mm-dd hh:mm:ss.

4.28 endOfToday()

Gets the date and time for the end of today in GMT.

4.28.1 Output Fields

Returns: the GMT end of today, in the format yyyy-mm-dd hh:mm:ss.

4.29 endOfYesterday()

Gets the date and time for the end of yesterday in GMT.

4.29.1 Output Fields

Returns: the GMT end of yesterday, in the format (yyyy-mm-dd huh:mm:ss).

4.30 hoursAgo(int)

Gets a date and time for a certain number of hours ago.

4.30.1 Input Fields

Parameters: An integer number of hours ago.

4.30.2 Output Fields

Returns: The (GMT) time that was the specified number of hours ago,in the format yyyy-mm-dd hh:mm:ss.

4.30.3 Example

if (current.operation() == 'insert') {
 // If no due date was specified, calculate a default
 if (current.due_date == '') {
 
  if (current.urgency == '1') {
   // Set due date to 4 hours ahead of current time
   current.due_date = gs.hoursAgo(-4);
  }
 
  if (current.urgency == '2') {
   // Set due date to 2 days ahead of current time
   current.due_date = gs.daysAgo(-2);
  }
 
  if (current.urgency == '3') {
   // Set due date to 7 days ahead of current time
   current.due_date = gs.daysAgo(-7);
  }
 }
}

4.31 hoursAgoEnd(int)

Gets a date and time for the end of the hour a certain number of hours ago.

4.31.1 Input Fields

Parameters: An integer number of hours ago.

4.31.2 Output Fields

Returns: The (GMT) end of the hour that was the specified number of hours ago, in the format yyyy-mm-dd hh:mm:ss.

4.32 hoursAgoStart(int)

Gets a date and time for the start of the hour a certain number of hours ago.

4.32.1 Input Fields

Parameters: An integer number of hours ago.

4.32.2 Output Fields

Returns: The (GMT) start of the hour that was the specified number of hours ago, in the format yyyy-mm-dd hh:mm:ss.

4.33 lastWeek()

Date and time one week ago in GMT.

4.33.1 Output Fields

Returns: the date and time one week ago, in the format yyyy-mm-dd hh:mm:ss.

4.34 minutesAgo(int)

Gets a date and time for a certain number of minutes ago.

4.34.1 Input Fields

Parameters: An integer number of minutes ago.

4.34.2 Output Fields

Returns: The (GMT) time that was the specified number of minutes ago, in the format yyyy-mm-dd hh:mm:ss.

4.34.3 Example

//
// Check to see if the user has failed to login too many times
// when the limit is reached, lock the user out of the system
//
  //Check failed logins in the last 15 minutes
  var gr = new GlideRecord('sysevent');
  gr.addQuery('name', 'login.failed');
  gr.addQuery('parm1', event.parm1.toString());
  gr.addQuery('sys_created_on','>=', gs.minutesAgo(15));
  gr.query();
  var rowCount = gr.getRowCount();
  if(rowCount >= 5){
      var gr = new GlideRecord("sys_user");
      gr.addQuery("user_name", event.parm1.toString());
      gr.query();
      if (gr.next()) {
           gr.locked_out = true;
           gr.update();
           gs.log("User " + event.parm1 + " locked out due to too many invalid login attempts");
      }
  }

4.35 minutesAgoEnd(int)

Gets a date and time for the end of the minute a certain number of minutes ago.

4.35.1 Input Fields

Parameters: An integer number of minutes ago.

4.35.2 Output Fields

Returns: The (GMT) end of the minute that was the specified number of minutes ago, in the format yyyy-mm-dd hh:mm:ss.

4.36 minutesAgoStart(int)

Gets a date and time for the start of the minute a certain number of minutes ago.

4.36.1 Input Fields

Parameters: An integer number of minutes ago.

4.36.2 Output Fields

Returns: The (GMT) start of the minute that was the specified number of minutes ago, in the format yyyy-mm-dd hh:mm:ss.

4.37 monthsAgo(int)

Gets a date and time for a certain number of months ago.

4.37.1 Input Fields

Parameters: An integer number of months ago.

4.37.2 Output Fields

Returns: The (GMT) beginning of the month that was the specified number of months ago, in the format yyyy-mm-dd hh:mm:ss.

4.38 monthsAgoEnd(int)

Gets a date and time for the last day of the month a certain number of months ago.

4.38.1 Input Fields

Parameters: An integer number of months ago.

4.38.2 Output Fields

Returns: The (GMT) end of the month that was the specified number of months ago, in the format yyyy-mm-dd hh:mm:ss.

4.39 monthsAgoStart(int)

Gets a date and time for the start of the minute a certain number of minutes ago.

4.39.1 Input Fields

Parameters: An integer number of minutes ago.

4.39.2 Output Fields

Returns: The (GMT) start of the minute that was the specified number of minutes ago, in the format yyyy-mm-dd hh:mm:ss.

4.40 now()

Gets the current date using GMT.

4.40.1 Output Fields

Returns: The current date in the user defined format, according to GMT.

4.40.2 Example

// When the user password changes then set the u_password_last_reset field
// to now so we know when to force another update
 
var gr = new GlideRecord("sys_user");
if (gr.get(event.parm1.toString())) {
    // Do something based on the Password Changing
    gs.log("The user password changed so do something else...");
    gr.u_password_last_reset = gs.now();
    gr.update();
}

4.41 nowNoTZ()

Gets the current date and time in UTC format.

4.41.1 Output Fields

Returns: the current UTC date time.

4.41.2 Example

// When the user password changes then set the u_password_last_reset field
// to now so we know when to force another update
 
var gr = new GlideRecord("sys_user");
if (gr.get(event.parm1.toString())) {
    // Do something based on the Password Changing
    gs.log("The user password changed so do something else...");
    gr.u_password_last_reset = gs.nowNoTZ();
    gr.update();
}

4.42 nowDateTime()

Gets the current date and time in the user-defined format.

4.42.1 Output Fields

Returns: The current date and time in the user-defined format.

4.42.2 Example

The following script sets the field u_target_date to the current date and time:

current.u_target_date = gs.nowDateTime();

After the script is run, the u_target_date field will hold the date and time of the moment the script is run, in the system format.

4.42.3 Example 2

When setting a variable in a workflow script to the current date and time, use the setDisplayValue method. The following script sets the workflow variable end_date to the current date and time:

current.variables.end_date.setDisplayValue(gs.nowDateTime());

After the script is run, the end_date field will hold the date and time of the moment the script is run, in the system format.

4.43 quartersAgo(int)

Gets a date and time for a certain number of quarters ago.

4.43.1 Input Fields

Parameters: An integer number of quarters ago.

4.43.2 Output Fields

Returns: The (GMT) beginning of the quarter that was the specified number of quarters ago, in the format yyyy-mm-dd hh:mm:ss.

4.44 quartersAgoEnd(int)

Gets a date and time for the last day of the quarter a certain number of quarters ago.

4.44.1 Input Fields

Parameters: An integer number of quarters ago.

4.44.2 Output Fields

Returns: The (GMT) end of the quarter that was the specified number of quarters ago, in the format yyyy-mm-dd hh:mm:ss.

4.45 quartersAgoStart(int)

Gets a date and time for the first day of the quarter a certain number of quarters ago.

4.45.1 Input Fields

Parameters: An integer number of quarters ago.

4.45.2 Output Fields

Returns: The (GMT) end of the month that was the specified number of quarters ago, in the format yyyy-mm-dd hh:mm:ss.

4.46 yearsAgo(int)

Gets a date and time for a certain number of years ago.

4.46.1 Input Fields

Parameters: An integer number of years ago.

4.46.2 Output Fields

Returns: The (GMT) beginning of the years that was the specified number of years ago, in the format yyyy-mm-dd hh:mm:ss.

4.47 yesterday()

Gets yesterday's time.

4.47.1 Output Fields

Returns: The (GMT) for 24 hours ago, in the format yyyy-mm-dd hh:mm:ss.

4.48 isFirstDayOfMonth(Object)

Checks whether the date is the first day of the month.

4.48.1 Input Fields

Parameters: date object.

4.48.2 Output Fields

Returns: true if date is the first day of the month, false if it is not.

4.49 isFirstDayOfWeek(Object)

Checks whether the date is the first day of the week. This uses the ISO standard of Monday being the first day of the week.

4.49.1 Input Fields

Parameters: date object.

4.49.2 Output Fields

Returns: true if date is the first day of the week, false if it is not.

4.50 isFirstDayOfYear(Object)

Checks whether the date is the first day of the year.

4.50.1 Input Fields

Parameters: date object.

4.50.2 Output Fields

Returns: true if date is the first day of the year, false if it is not.

4.51 isLastDayOfMonth(Object)

Checks whether the date is the last day of the month.

4.51.1 Input Fields

Parameters: date object.

4.51.2 Output Fields

Returns: true if date is the last day of the month, false if it is not. This uses the ISO standard of Sunday being the last day of the week.

4.52 isLastDayOfWeek(Object)

Checks whether the date is the last day of the week.

4.52.1 Input Fields

Parameters: date object.

4.52.2 Output Fields

Returns: true if date is the last day of the week, false if it is not.

4.53 isLastDayOfYear(Object)

Checks whether the date is the last day of the year.

4.53.1 Input Fields

Parameters: date object.

4.53.2 Output Fields

Returns: true if date is the last day of the year, false if it is not.

5 User Session

5.1 addErrorMessage(Object)

Adds an error message for the current session. Can be accessed using getErrorMessages()

5.1.1 Input Fields

Parameters: an error object.

5.1.2 Example

 gs.include("PrototypeServer");
  var ValidatePasswordStronger = Class.create();
  ValidatePasswordStronger.prototype = {
       process : function() {
          var user_password = request.getParameter("user_password");
          var min_len = 8;
          var rules = "Password must be at least " + min_len + 
             " characters long and contain a digit, an uppercase letter, and a lowercase letter.";
          if (user_password.length() < min_len) {
             gs.addErrorMessage("TOO SHORT: " + rules);
             return false;
          }
          var digit_pattern = new RegExp("[0-9]", "g");
          if (!digit_pattern.test(user_password)) {
             gs.addErrorMessage("DIGIT MISSING: " + rules);
             return false;
          }
          var upper_pattern = new RegExp("[A-Z]", "g");
          if (!upper_pattern.test(user_password)) {
             gs.addErrorMessage("UPPERCASE MISSING: " + rules);
             return false;
          }
          var lower_pattern = new RegExp("[a-z]", "g");
          if (!lower_pattern.test(user_password)) {
             gs.addErrorMessage("LOWERCASE MISSING: " + rules);
             return false;
          }
          return true; // password is OK
       }
  }

5.2 addInfoMessage(Object)

Adds an info message for the current session. Can be called using getInfoMessages(). Note: This method is not supported for asynchronous business rules.

5.2.1 Input Fields

Parameters: an info message object.

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

5.3 addMessage(String, Object)

Adds a message for the current session. Can be called using getMessages(String).

5.3.1 Input Fields

Parameters:

  • String type of message
  • Message to store

5.3.2 Example

gs.include("FormInfoHeader");
var fi = new FormInfoHeader();
var s = 'An incident ' + current.number + ' has been opened for your request.<br/>';
s += 'The IT department will contact you when the password is reset or for further information.<br/>';
//s += 'You can track status from the <a href="home.do" class="breadcrumb" >Home Page</a> <br/>';
fi.addMessage(s);
producer.redirect = 'home.do?sysparm_view=ess';

5.4 clearClientData(String)

Clears a specified session client name/value pair previously set with putClientData().

5.4.1 Input Fields

Parameters:

  • The name of the value pair to clear.

5.5 flushMessages()

Clears any session messages saved using addErrorMessage(Object) or addInfoMessage(Object).

5.5.1 Output Fields

Returns: void

5.6 getClientData(String)

Gets a session client value previously set with putClientData().

5.6.1 Input Fields

Parameters:

  • The name of the session client name/value pair.

5.6.2 Output Fields

Returns: the client data as a string.

5.7 getErrorMessages()

Gets the list of error messages for the session that were added by addErrorMessage(Object)

5.7.1 Output Fields

Returns: list of error messages.

5.8 getImpersonatingUserDisplayName()

Returns the display name of the impersonating user.

5.8.1 Output Fields

Returns: display name of impersonating user.

5.9 getImpersonatingUserName()

Return the name of the impersonating user or null if not impersonating

5.9.1 Output Fields

Returns: name of the impersonating user.

5.10 getInfoMessages()

Gets the list of info messages for the session that were added via addInfoMessage(Object).

5.10.1 Output Fields

Returns: the list of info messages.

5.11 getMessages(String)

Gets the list of messages of the specified type for the session that were added via addMessage(String, Object).

5.11.1 Input Fields

Parameters: string type of message.

5.11.2 Output Fields

Returns: list of messages of string type.

5.12 getNodeValue(object, Integer)

Gets the node value for specified index.

5.12.1 Input Fields

Parameters

  • Object to examine.
  • Integer for the index to get a node value from.

5.12.2 Output Fields

Returns: the node's value. == getNodeName(Object, Integer)

Returns the node name for specified index.

5.12.3 Input Fields

Parameters

  • Object to examine.
  • Integer for the index to get a node value from.

5.12.4 Output Fields

Returns: the node's name.

5.13 getPreference(String, Object)

Gets a user preference.

5.13.1 Input Fields

Parameters:

  • String key for the preference.
  • Object default value

5.13.2 Output Fields

Returns: a string value for the preference. If null, uses the default value specified above.

5.14 getRoles()

Gets a list of roles for the current user. The list of roles does not reflect any changes made during the current user session. To get the updated list of roles, the user must log out and log back in.

5.14.1 Output Fields

Returns: (String) A list of comma-separated roles.

5.14.2 Example

gs.print(gs.getSession().getRoles());

Output:

***
Script: admin,security_admin

5.15 getSession()

Gets a reference to the current Glide session.

5.15.1 Output Fields

Returns: a string reference for the current session.

5.15.2 Example

if (!gs.hasRole("admin") && !gs.hasRole("user_admin") && gs.getSession().isInteractive()) {
  current.addQuery("active", "true");
}

5.16 getSessionID()

Accesses the GlideSession Session ID.

5.16.1 Output Fields

Returns: the Session ID.

5.17 getTrivialMessages()

Gets the list of error messages for the session that were added with the trivial flag.

5.17.1 Output Fields

Returns: the list of messages.

5.18 getUser()

Returns a reference to the User object for the current user. More information is available here.

5.18.1 Output Fields

Returns: a reference to a User object.

5.18.2 Example

var myUserObject = gs.getUser()

5.19 getUserDisplayName()

Returns the name field of the current user (e.g. John Smith, as opposed to jsmith).

5.19.1 Output Fields

Returns: the name field of the current user (e.g. John Smith, as opposed to jsmith).

5.19.2 Example

    <g2:evaluate var="jvar_current_user" expression="gs.getUserDisplayName()"/>
     $[JS:jvar_current_user]

5.20 getUserID()

Returns the sys_id of the current user.

5.20.1 Output Fields

Returns: the sys_id of the current user.

5.20.2 Example

if (current.operation() != ‘insert’ && current.comments.changes()) {
    gs.eventQueue(“incident.commented, current, gs.getUserID(), gs.getUserName());
}

5.21 getUserName()

Returns the username of the current user (e.g., jsmith).

5.21.1 Output Fields

Returns: the username of the current user (e.g., jsmith).

5.21.2 Example

//Add a comment when closing
    current.comments = "Closed by " + gs.getUserName() + " at " + gs.nowDateTime();
    gs.addInfoMessage("Close comment added");
}

5.22 getUserNameByUserID(String)

Gets the username based on a user ID.

5.22.1 Input Fields

Parameters: a sys_id as a string.

5.22.2 Output Fields

Returns: the username.

5.23 getXMLText (String, String)

Gets the xml text for the first node in the xml string that matches the xpath query.

5.23.1 Input Fields

Parameters:

  • XML to search within
  • xpath query to match

5.23.2 Output Fields

Returns: the XML node value as text.

5.24 getXMLNodeList(String)

Constructs an Array of all the nodes and values in an XML document.

5.24.1 Input Fields

Parameters: XML document to parse.

5.24.2 Output Fields

Returns: an array list of names and values.

5.25 hasRole(String)

Determines if the current user has the specified role. This method returns true for users with the administrator role.

5.25.1 Input Fields

Parameters: the role to check.

5.25.2 Output Fields

Returns: true if the user has the role or false if the user does not have the role.

5.25.3 Example

if (!gs.hasRole("admin") && !gs.hasRole("groups_admin") && gs.getSession().isInteractive()) {
  var qc = current.addQuery("u_hidden", "!=", "true"); //cannot see hidden groups... 
  qc.addOrCondition("sys_id", "javascript:getMyGroups()"); //...unless in the hidden group
}

5.26 hasRoleInGroup(Object, Object)

Determines if the current user has the specified role within a specified group.

5.26.1 Input Fields

Parameters:

  • The name of the role to check for.
  • A GlideRecord or the sys_id of the group to check within.

5.26.2 Output Fields

Returns: Returns true if all of the following conditions are met:

  1. The logged-in user HAS the role in question
  2. The "Granted by" field on the user role record is set to the specified group
  3. The "inherited" field on the user role record is false

5.26.3 Example

var group = new GlideRecord('sys_user_group');
group.addQuery('name', 'GROUP_NAME');
group.setLimit(1);
group.query();
if (group.next()) {
   if (gs.hasRoleInGroup('role_name', group)) {
      gs.print('User has role in group');  
   } else {
      gs.print('User does NOT have role in group');
   }  
}

5.27 isInteractive()

Checks if the current session is interactive. An example of an interactive session is when a user logs in normally. An example of a non-interactive session is using a SOAP request to retrieve data.

5.27.1 Output Fields

Returns: true if the session is interactive.

5.27.2 Example

if (!gs.hasRole("admin") && gs.getSession().isInteractive()) {
 var qc1 = current.addQuery('u_group',"");
var gra = new GlideRecord('sys_user_grmember');
gra.addQuery('user', gs.getUserID());
gra.query();
while (gra.next()) {
  qc1.addOrCondition('u_group', gra.group);
}
 
}

5.28 isLoggedIn()

Determines if the current user is currently logged in.

5.28.1 Output Fields

Returns: true if the current user is logged in, false if the current user is not.

5.29 setRedirect(Object)

Sets the redirect URI for this transaction. This determines the next page the user will see.


5.29.1 Input Fields

Parameters: URI object to set as redirect.

5.29.2 Example

The following example redirects the user to a particular Catalog Item, and passes along the current email as a parameter:

gs.setRedirect("com.glideapp.servicecatalog_cat_item_view.do?sysparm_id=d41ce5bac611227a0167f4bf8109bf70&sysparm_user=" 
+ current.sys_id + "&sysparm_email=" + current.email)

5.30 putClientData(String, String)

Sets a name/value pair that is associated with the current session and made available on the client for use in client scripts.

5.30.1 Input Fields

Parameters:

  • The name for the name/value pair.
  • The value for the name/value pair.

5.31 setReturn(Object)

Sets the return URI for this transaction. This determines what page the user will be directed to when they return from the next form.

5.31.1 Input Fields

Parameters: URI object to set as return.

5.31.2 Example

The following example ensures that the user will be returned to the current page when they are done with the next one.

   gs.setReturn (current.getLink(true));

5.32 userID()

Returns the sys_id of the user associated with this session. A shortcut for the more proper getUserID().

5.32.1 Output Fields

Returns: sys_id of current user.

Was this article helpful?
Yes, I found what I needed
No, I need more assistance
Views
Personal tools