Riya Verma
Kilo Sage

Introduction to ServiceNow GlideSystem API

One of the powerful features of ServiceNow is the GlideSystem API, which provides a plethora of methods to retrieve information about the system, the current logged-in user, and date/time information, among others. This article will delve into a detailed exploration of various essential methods offered by the GlideSystem API.

 

GlideSystem - Global

The GlideSystem API, globally accessible through the variable name ‘gs’ in server-side JavaScript, is a powerful tool that facilitates various functionalities such as error handling, event management, and message display, enhancing the overall user experience and system functionality.

 

addErrorMessage Method

Description:

The addErrorMessage method is used to add an error message for the current session, which can be retrieved later. This is particularly useful for validation and user feedback during form submissions or data processing.

Inputs:

  • message: The error message is to be added.

Outputs:

  • No return value (void).
gs.include("PrototypeServer");
var ValidatePasswordStronger = Class.create();
ValidatePasswordStronger.prototype = {
    process: function() {
        var user_password = request.getParameter("user_password");
        var rules = "Password must be at least 8 characters long and contain a digit, an uppercase letter, and a lowercase letter.";
        if (user_password.length < 😎 {
            gs.addErrorMessage("TOO SHORT: " + rules);
            return false;
        }
        // Additional validations here...
        return true; // password is OK
    }
}

 

addInfoMessage Method

Description:

The addInfoMessage method is instrumental in adding informational messages to the current session. These messages can be used to guide or inform the user regarding the operations being performed.

Inputs:

  • message: The informational message to be added.

Outputs:

  • No return value (void).
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);
    }
}

 

addMessage Method

Description:

The addMessage method is a generic method to add messages of various types, such as error or info, to the current session. It provides a flexible way to communicate different types of messages to the users.

Inputs:

  • type: Type of message, such as error or info.
  • message: The message to be added to the current session.

Outputs:

  • No return value (void).
// Define a function to demonstrate the usage of addMessage method
function demonstrateAddMessage() {
    // Adding an info message
    gs.addMessage('info', 'This is an informational message.');

    // Adding an error message
    gs.addMessage('error', 'An error occurred while processing your request.');

    // Adding a custom type of message
    gs.addMessage('custom', 'This is a custom type message.');
}

//You can call the demonstrateAddMessage function in a server-side script, such as a business rule or script include, to execute the demonstration. 

// Calling the function to execute the demonstration
demonstrateAddMessage();

 

eventQueue Method

Description:

The eventQueue method allows queuing an event for the event manager, facilitating asynchronous processing and enhancing system performance and responsiveness.

Inputs:

  • name: Name of the event being queued.
  • glideRecord: GlideRecord object, such as "current".
  • parm1 and parm2: Optional parameters saved with the instance if specified.

Outputs:

  • No return value (void).
if (current.operation() != 'insert' && current.comments.changes()) {
    gs.eventQueue("incident.commented", current, gs.getUserID(), gs.getUserName());
}

 

eventQueueScheduled Method

Description:

The eventQueueScheduled method is similar to the eventQueue method but allows scheduling the event for a specific date and time, providing enhanced control over event processing.

Inputs:

  • name: Name of the event being queued.
  • glideRecord: GlideRecord object, such as "current".
  • parm1, parm2, and expiration: Parameters specifying additional event details and scheduling.

Outputs:

  • No return value (void).
if (current.operation() != 'insert' && current.comments.changes()) {
    gs.eventQueueScheduled("incident.commented", current, gs.getUserID(), gs.getUserName(), new GlideDateTime('2018-06-02 20:00:00'));
}

 

getDisplayValueFor Method

Description:

The getDisplayValueFor method is used to retrieve the display value of a specified field on a specified record in a particular table. This method is useful for getting readable values for reference fields or choice fields where the actual value stored in the database might be a sys_id or numeric value.

Inputs:

  • tableName: A string representing the name of the table.
  • recordID: A string representing the sys_id of the record.
  • fieldName: A string representing the name of the field.

Outputs:

  • Returns a string representing the display value of the specified field.
var value = gs.getDisplayValueFor(current.getTableName(), current.getValue('sys_id'), 'number');
gs.info('Display value for the field: ' + value);

 

flushMessages Method

Description:

The flushMessages method in the GlideSystem API is used to clear all session messages that were previously saved using addErrorMessage() or addInfoMessage(). These session messages are typically displayed at the top of the form and can be cleared to manage the messages shown to the user effectively.

Inputs:

  • None

Outputs:

  • No return value (void).
function clearSessionErrors() {
    var msgs = gs.getErrorMessages().toArray();
    if (msgs.length > 0) {
        gs.flushMessages();
        gs.info('Session messages have been cleared.');
    }
}

 

getCurrentScopeName Method

Description:

The getCurrentScopeName method returns the name of the current application scope in ServiceNow. Knowing the current scope is essential to ensure that the correct resources, such as scripts and workflows, are being accessed and executed within the intended application scope.

Inputs:

  • None

Outputs:

  • Returns a string representing the current scope name.
var incident_GR = new GlideRecord('Incident');

if (incident_GR.get("2e3f6baddb9ad600added8fdbf9618cb")) {
    gs.debug("Processor scope = " + gs.getCurrentScopeName());
    // Additional code here...
}

 

getDateFormat Method

Description:

The getDateFormat method returns the date format associated with the current user in ServiceNow. This is useful for formatting and displaying dates according to the user’s preferences and locale.

Inputs:

  • None

Outputs:

  • Returns a string representing the date format associated with the current user.
var userDateFormat = gs.getDateFormat();
gs.info(userDateFormat); // Output: yyyy-MM-dd

 

getDateTimeFormat Method

Description:

The getDateTimeFormat method is used to retrieve the date and time format associated with the current user in ServiceNow. This allows for the consistent presentation of date and time values in a format that aligns with the user’s preferences.

Inputs:

  • None

Outputs:

  • Returns a string representing the date and time format associated with the current user.
var userDateTimeFormat = gs.getDateTimeFormat();
gs.info(userDateTimeFormat); // Output: yyyy-MM-dd HH:mm:ss

 

getUser Method

Description:

The getUser method returns a reference to the user object for the current user in ServiceNow. This allows for the retrieval of various user attributes and details, facilitating user-specific customizations and functionalities.

Inputs:

  • None

Outputs:

  • Returns a GlideUser object representing the current user.
var user = gs.getUser();
gs.print("The current user is: " + user);

 

getUserID Method

Description:

The getUserID method returns the sys_id of the current user. This unique identifier can be used to reference specific user records within various parts of the application.

Inputs:

  • None

Outputs:

  • Returns a string representing the sys_id of the current user.
var currentUserId = gs.getUserID();
gs.print("Current user ID: " + currentUserId);

 

getUserName Method

Description:

The getUserName method returns the username of the current user. This is the unique name that the user uses to log in to the ServiceNow application.

Inputs:

  • None

Outputs:

  • Returns a string representing the username of the current user.
var user = gs.getUserName();
gs.print("The current user name is: " + user);

 

userID Method

Description:

The userID method is similar to getUserID, returning the sys_id of the user associated with the current session. However, it's recommended to use getUserID instead for consistency and clarity.

Inputs:

  • None

Outputs:

  • Returns a string representing the sys_id of the current user.
var currentUserSysId = gs.userID();
gs.print("Current user sys_id: " + currentUserSysId);

 

hasRole Method

Description:

The hasRole method determines if the current user has a specific role or any one of multiple roles passed as a comma-separated string. It is essential for controlling access and permissions within various functionalities of the application.

Inputs:

  • roleName: A string or a comma-separated list of roles.

Outputs:

  • Returns a boolean value indicating whether the current user has at least one of the specified roles.
if (gs.hasRole("admin, groups_admin")) {
    gs.print("User has the admin or groups_admin role.");
} else {
    gs.print("User does not have the admin or groups_admin role.");
}

 

hasRoleInGroup Method

Description:

The hasRoleInGroup method checks whether the current user has a specific role within a specified group. This is useful for more granular access control based on user roles within specific groups.

Inputs:

  • roleName: The name of the role.
  • group: The sys_id of the group.

Outputs:

  • Returns a boolean value indicating whether the current user has the specified role within the specified group.
var group = new GlideRecord('sys_user_group');
group.get('name', 'GROUP_NAME');

if (gs.hasRoleInGroup('role_name', group.sys_id)) {
    gs.print('User has role in group');
} else {
    gs.print('User does NOT have role in group');
}

 

 

 

 

Comments
AnubhavRitolia
Mega Sage

@Riya Verma 

 

Quite useful articles.

 

Version history
Last update:
‎10-26-2023 02:19 AM
Updated by:
Contributors