ServiceNow GlideSystem API (Quebec)
Adds an error message for the current session.
addErrorMessage(Object message) 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."; gs.addErrorMessage("TOO SHORT: " + rules); return false;
Adds an info message for the current session.
addInfoMessage(Object message) gs.addInfoMessage('start must be before end');
Adds a message for the current session.
addMessage(String type, Object message) type : 'error' or 'info'
Gets the date and time for the beginning of last month in GMT.
beginningOfLastMonth() Returns The GMT beginning of last month, in the format yyyy-mm-dd hh:mm:ss.
Returns the date and time for the beginning of last week in GMT.
beginningOfLastWeek() Returns the GMT beginning of last week, in the format yyyy-mm-dd hh:mm:ss.
Returns the date and time for the beginning of next month in GMT.
beginningOfNextMonth() Returns the GMT beginning of next month, in the format yyyy-mm-dd hh:mm:ss.
Gets the date and time for the beginning of next week in GMT.
beginningOfNextWeek() Returns the GMT beginning of next week, in the format yyyy-mm-dd hh:mm:ss.
Returns the date and time for the beginning of next year in GMT.
beginningOfNextYear() The GMT beginning of next year, in the format yyyy-mm-dd hh:mm:ss.
Returns the date and time for the beginning of this month in GMT.
beginningOfThisMonth() The GMT beginning of this month, in the format yyyy-mm-dd hh:mm:ss.
Returns the date and time for the beginning of this quarter in GMT.
beginningOfThisQuarter() The GMT beginning of this quarter, in the format yyyy-mm-dd hh:mm:ss.
Returns the date and time for the beginning of this week in GMT.
beginningOfThisWeek() Returns a string of the GMT beginning of this week, in the format yyyy-mm-dd hh:mm:ss.
Returns the date and time for the beginning of this year in GMT.
beginningOfThisYear() Returns a string of the GMT beginning of this year, in the format yyyy-mm-dd hh:mm:ss
Retrieves the date and time for the beginning of today in GMT.
beginningOfToday() Returns a string of the GMT beginning of today, in the format yyyy-mm-dd hh:mm:ss. var beginToday = gs.beginningOfToday(); gs.info('beginningOfToday: ' + beginToday);
Retrieves the (UTC) beginning of tomorrow adjusted for the timezone of the current session.
beginningOfTomorrow() Returns GMT in the format yyyy-mm-dd hh:mm:ss. var beginTomorrow = gs.beginningOfTomorrow(); gs.info('beginningOfTomorrow: ' + beginTomorrow);
Retrieves the date and time for the beginning of yesterday in GMT.
beginningOfYesterday() Returns the GMT beginning of yesterday, in the format yyyy-mm-dd hh:mm:ss. var start = new GlideDateTime(); start.setValue(gs.beginningOfYesterday());
Calculate the difference between two dates using the default calendar. Calendars are now legacy. If Schedules are being used, see the topic Calculate Duration Given a Schedule.
calDateDiff(String startDate, String endDate, Boolean numericValue) numericValue : If true, the return value will be formatted in number of seconds; if false the return value will be formatted ddd hh:mm:ss.
Calculates the difference between two dates.
dateDiff(String startDate, String endDate, Boolean numericValue) date1.setDisplayValueInternal('2014-01-01 12:00:00'); date2.setDisplayValueInternal('2014-01-01 13:00:00'); var diffSeconds = gs.dateDiff(date1.getDisplayValue(), date2.getDisplayValue(), true);
Generates a date and time for the specified date in GMT.
dateGenerate(String date, String range) date : yyyy-mm-dd range : Start, end, or a time in the 24-hour format hh:mm:ss. Returns date and time in the format yyyy-mm-dd hh:mm:ss.
Returns a date and time for a certain number of days ago.
daysAgo(Number days) gs.daysAgo(-50); Returns the GMT in the format yyyy-mm-dd hh:mm:ss.
Returns a date and time for the end of the day a specified number of days ago.
daysAgoEnd(Number days) days : Integer number of days Returns the GMT end of the day in the format yyyy-mm-dd hh:mm:ss.
Returns the date and time of the beginning of the day for the specified number of days ago. The returned date and time reflect the time zone of the current session (local time).
daysAgoLocal(Number days) if (due_in == "1 Day") { dd = gs.daysAgoLocal(-1); } if (due_in == "1 Week") { dd = gs.daysAgoLocal(-7); }
Returns a date and time for the beginning of the day a specified number of days ago.
daysAgoStart(Number days) var now_GR = new GlideRecord('sysapproval_approver'); now_GR.addQuery('state', 'requested'); now_GR.addQuery('sys_updated_on', '<', gs.daysAgoStart(5)); now_GR.query();
Returns the date and time for the end of last month in GMT.
endOfLastMonth() Returns the GMT end of last month, in the format yyyy-mm-dd hh:mm:ss.
Returns the date and time for the end of last week in GMT.
endOfLastWeek() Returns a string of GMT end of last week, in the format yyyy-mm-dd hh:mm:ss
Returns the date and time for the end of last year in GMT.
endOfLastYear() Returns a string of GMT in format yyyy-mm-dd hh:mm:ss.
Returns the date and time for the end of next month in GMT.
endOfNextMonth() Returns a string of the GMT in the format yyyy-mm-dd hh:mm:ss.
Gets the date and time for the end of next week in GMT.
endOfNextWeek() Returns the GMT in the format yyyy-mm-dd hh:mm:ss.
Returns the date and time for the end of next year in GMT.
endOfNextYear() Returns a string of the GMT in the format yyyy-mm-dd hh:mm:ss.
Returns the date and time for the end of this month in GMT.
endOfThisMonth() Returns a string of the GMT in the format (yyyy-mm-dd huh:mm:ss)
Returns the date and time for the end of this quarter in GMT.
endOfThisQuarter() Returns a string of the GMT in the format yyyy-mm-dd hh:mm:ss.
Returns the date and time for the end of this week in GMT.
endOfThisWeek() Returns a string of the GMT in the format yyyy-mm-dd hh:mm:ss.
Returns the date and time for the end of this year in GMT.
endOfThisYear() Returns a string of the GMT in the format yyyy-mm-dd hh:mm:ss.
Retrieves the date and time for the end of today in GMT.
endOfToday() var endToday = gs.endOfToday(); gs.info('endOfToday: ' + endToday);
Retrieves the date and time for the end of tomorrow in GMT.
endOfTomorrow() var tomorrowEnd = new GlideDateTime(); tomorrowEnd.setValue(gs.endOfTomorrow());
Gets the date and time for the end of yesterday in GMT.
endOfYesterday() var yesterdayEnd = new GlideDateTime(); yesterdayEnd.setValue(gs.endOfYesterday());
Queues an event for the event manager.
eventQueue(String name, Object glideRecord, String parm1?, String parm2?, String queue) name : Name of the event being queued. glideRecord : GlideRecord object, such as "current". queue : Name of the queue. gs.eventQueue("incident.commented", current, gs.getUserID(), gs.getUserName());
Queues an event for the event manager at a specified date and time.
eventQueueScheduled(String name, Object glideRecord, String parm1, String parm2, Object expiration) gs.eventQueueScheduled("incident.commented", current, gs.getUserID(), gs.getUserName(), new GlideDateTime('2018-06-02 20:00:00')); }
Clears session messages saved using addErrorMessage() or addInfoMessage().
flushMessages() Session messages are shown at the top of the form. In client side scripts, use g_form.clearMessages() to remove session messages.
Returns the file path to the user's avatar.
getAvatar() Example: var avatarFile = gs.getUser().getAvatar(); gs.addInfoMessage('User avatar ID: ' + avatarFile); Output: User avatar ID: c148e1d13741310042106710ce41f149.iix?t=small
Gets the name of the current scope.
getCurrentScopeName()
Retrieves the display column for the table.
getDisplayColumn(String tableName) tableName : Name of the table from which to get the display column name.
Returns the display value for a specified field on a record.
getDisplayValueFor(String tableName, String recordID, String fieldName) tableName : Name of the table recordID : sysid for the record fieldName : Name of the field
Returns the list of error messages for the session that were added by addErrorMessage().
getErrorMessages()
Retrieves the property and escapes it for XML parsing.
getEscapedProperty(String key, Object substituteObject) key : Key for the property whose value should be returned. substituteObject : Object to be returned if the property is not found. Returns the property, or the substituteObject if the property is not found.
Returns the display name of the impersonating user.
getImpersonatingUserDisplayName()
Returns the name of the impersonating user or null if not impersonating.
getImpersonatingUserName()
Retrieves the list of info messages for the session that were added by addInfoMessage(). Returns
getInfoMessages()
Returns the user's initials.
getInitials() var userInitials = gs.getUser().getInitials(); gs.addInfoMessage('User initials: ' + userInitials); Output: User initials: SA
Retrieves translated messages from the Message [sys_ui_message] table to display in a UI.
getMessage(String messageID, Object args) // current.action.name is "update record" var my_message = gs.getMessage("Abort adding action '{0}', same subflow can't be added twice in this subflow.", current.action.name); alert(my_message); Output: Abort adding action update record, same subflow can't be added twice in this subflow.
Retrieves translated messages to display in the UI and escapes all ticks (').
getMessageS(String messageID, Object args) var my_message = '${gs.getMessageS("I love France")}'; alert(my_message); Output: J'aime la France
Returns the list of messages of the specified type for the session that were added by addMessage().
getMessages(String type)
Returns the node name for specified index.
getNodeName(Object obj, Number index) obj : Object to examine index : Index from which to get the node name Returns the node's name
Returns the node value for specified index.
getNodeValue(Object obj, Number index) Returns the node's value
Returns a user preference.
getPreference(String key, Object default) key : The key for the preference default : The default value Returns the preference. If no preference, returns the specified default value.
Gets the value of a Glide property. If the property is not found, returns the alternate value.
getProperty(String key, Object alt?) //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(); } }
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.
getScriptError(String script) script : The script to check for errors. Returns the error message, or null if there is no error.
Returns a GlideSession object.
getSession()
Returns the GlideSession Session ID.
getSessionID()
Returns the style defined for the table, field and value.
getStyle(String tableName, String fieldName, String fieldValue)
Returns the list of error messages for the session that were added with the trivial flag.
getTrivialMessages() Returns a string list of messages
Returns a reference to the user object for the current user.
getUser()
Returns the name field of the current user. For example, the API returns John Smith instead of jsmith.
getUserDisplayName() var user = gs.getUserDisplayName(); gs.print ("The current user display name is: " + user); Output : The current user display name is: abel.tuter
Returns the sys_id of the current user.
getUserID() if (current.operation() != 'insert' && current.comments.changes()) { gs.eventQueue("incident.commented", current, gs.getUserID(), gs.getUserName()); }
Returns the username of the current user (e.g., jsmith).
getUserName() //Add a comment when closing current.comments = "Closed by " + gs.getUserName() + " at " + gs.nowDateTime(); gs.addInfoMessage("Close comment added"); }
Returns the username based on a user ID.
getUserNameByUserID(String sys_id)
Constructs an Array of all the nodes and values in an XML document.
getXMLNodeList(String xml)
Returns the XML text for the first node in the XML string that matches the XPath query.
getXMLText(String xml, String xpathQuery)
Determines if the current user has at least one of the passed-in roles.
hasRole(String roleName) if (!gs.hasRole("admin, 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 }
Determines if the current user has the specified role within a specified group.
hasRoleInGroup(Object roleName, Object group) 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'); } }
Returns a date and time for a certain number of hours ago.
hoursAgo(Number hours)
Returns a date and time for the end of the hour a certain number of hours ago.
hoursAgoEnd(Number hours)
Returns a date and time for the start of the hour a certain number of hours ago.
hoursAgoStart(Number hours)
Checks whether the date is the first day of the month.
isFirstDayOfMonth(Object date) var gdt = new GlideDateTime(); gdt.setValue('2021-04-01 12:00:00'); var currentDay = gs.isFirstDayOfMonth(gdt); gs.print("First day of month: " + currentDay); Output : First day of month: true
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.
isFirstDayOfWeek(Object date) var gdt = new GlideDateTime(); gdt.setValue('2021-04-01 12:00:00'); var currentDay = gs.isFirstDayOfWeek(gdt); gs.print("First day of week: " + currentDay); Output : First day of week: true
Checks whether the date is the first day of the year.
isFirstDayOfYear(Object date)
Checks if the current session is interactive.
isInteractive() An example of an interactive session is when a user logs in using the log-in screen. An example of a non-interactive session is using a SOAP request to retrieve data.
Checks whether the date is the last day of the week.
isLastDayOfWeek(Object date)
Checks whether the date is the last day of the year.
isLastDayOfYear(Object date)
Checks whether the date is the last day of the month.
isLastDayofMonth(Object date)
Determines if the current user is currently logged in.
isLoggedIn()
Determines whether a request comes from a mobile device. This method can be used in UI action conditions and business rules.
isMobile() if (gs.isMobile()) gs.info("submitted from mobile UI"); else gs.info("NOT submitted from mobile UI");
Returns the date and time one week ago in GMT.
lastWeek()
Logs a message to the system log and saves it to the syslog table.
log(String message, String source?)
Logs an error to the system log and saves it to the syslog table.
logError(String message, String source)
Logs a warning to the system log and saves it to the syslog table.
logWarning(String message, String source)
Returns a date and time for a certain number of minutes ago
minutesAgo(Number minutes)
Returns a date and time for the end of the minute a certain number of minutes ago. Parameters
minutesAgoEnd(Number minutes)
Returns a date and time for the start of the minute a certain number of minutes ago.
minutesAgoStart(Number minutes)
Returns a date and time for a certain number of months ago.
monthsAgo(Number months)
Returns a date and time for the last day of the month a certain number of months ago.
monthsAgoEnd(Number months)
Returns a date and time for the start of the month a certain number of months ago.
monthsAgoStart(Number months)
Queries an object and returns true if the object is null or contains an empty string.
nil(Object obj)
Returns the current date in UTC.
now() var now_GR = new GlideRecord("sys_user"); if (now_GR.get(event.parm1.toString())) { // Do something based on the Password Changing gs.log("The user password changed so do something else..."); now_GR.u_password_last_reset = gs.now(); now_GR.update(); }
Gets the current date and time in the user-defined format.
nowDateTime() current.u_target_date = gs.nowDateTime(); or current.variables.end_date.setDisplayValue(gs.nowDateTime());
Gets a GlideDateTime object with the current date and time.
nowGlideDateTime() current.u_target_date = gs.nowGlideDateTime();
Returns the current date and time in UTC format.
nowNoTZ() var now_GR = new GlideRecord("sys_user"); if (now_GR.get(event.parm1.toString())) { // Do something based on the Password Changing gs.log("The user password changed so do something else..."); now_GR.u_password_last_reset = gs.nowNoTZ(); now_GR.update(); }
Writes a message to the system log. This method does not write the message to the syslog table unless debug has been activated.
print(String message) var rec = new GlideRecord('incident'); rec.addQuery('active',false); rec.query(); while (rec.next()) { gs.print('Inactive incident ' + rec.number + ' deleted'); rec.deleteRecord(); }
Returns a date and time for a certain number of quarters ago.
quartersAgo(Number quarters)
Returns a date and time for the last day of the quarter, for a specified number of quarters ago.
quartersAgoEnd(Number quarters)
Returns a date and time for the first day of the quarter, for a specified number of quarters ago.
quartersAgoStart(Number quarters)
Sets the specified key to the specified value. Note: Care should be taken when setting system properties (sys_properties) using this method as it causes a system-wide cache flush. Each flush can cause system degradation while the caches rebuild.
setProperty(String key, String value, String description) gs.setProperty("glide.foo","bar","foo"); gs.info(gs.getProperty("glide.foo")); Output: foo
Sets the redirect URI for this transaction, which then determines the next page the user will see.
setRedirect(Object URI) This 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)
Sets the return URI for this transaction. This determines what page the user will be directed to when they return from the next form.
setReturn(Object URI) This ensures that the user will be returned to the current page when they are done with the next one. gs.setReturn (current.getLink(true));
Determines if a database table exists.
tableExists(String tableName)
Returns the sys_id of the user associated with this session. Use getUserID() instead.
userID()
Deletes any open scheduled job records in the Schedule (sys_trigger) table for the specified GlideRecord.
workflowFlush(Object glideRecord)
Gets a date and time for a certain number of years ago.
yearsAgo(Number years)
Returns yesterday's time (24 hours ago).
yesterday()
GlideSystem
The GlideSystem (referred to by the variable name 'gs' in any server-side JavaScript) API provides a number of convenient methods to get information about the system, the current logged in user, etc. Many of the GlideSystem methods facilitate the easy inclusion of dates in query ranges, and are most often used in filters and reporting.