GROW

code

Avoid using g_form.getReference()

This issue is found automatically by CODA.
Time to fix: 02h 30min

What is a reference field in ServiceNow?

In ServiceNow, a reference field is a type of field that connects records between tables by pointing to entries in another table. Reference fields allow you to associate one record with another, facilitating data linkage. When you choose a value in a reference field, it typically corresponds to a specific record in a different table.

For example, in an incident table, you might include a reference field that indicates the user linked to a particular incident. This type of field contributes to a more interconnected data model in ServiceNow, promoting data consistency across diverse tables.

Why is this an issue?

The g_form.getReference() method retrieves the complete record, implying that it fetches the entire object with all field values from the server. This extensive data request can lead to latency in your Client Side action, potentially impacting the performance of the instance, especially in common scenarios where this level of detail is not required.

How do I fix it?

Another approach to fetch data from the server is by utilizing the GlideAjax API. Alternatively, you can achieve this task using a REST API. The following code illustrates how to retrieve, for instance, the manager user:

  • Server side:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var getUserData = Class.create();
getUserData.prototype = Object.extendsObject(AbstractAjaxProcessor, {
  getUserSomeData: function (user_id, user_field) {
    user_id = user_id || this.getParameter("sysparm_user_id");
    user_field = user_field || this.getParameter("sysparm_user_field");

    if (!user_id || !user_field) {
      return "";
    }

    var getUser = new GlideRecord("sys_user");
    if (getUser.get(user_id)) {
      // Return the value to Client Side
      return getUser.getDisplayValue(user_field);
    }
  },
  type: "getUserData",
});
  • Client side:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// GlideAjax receives Script Include name as the first parameter
var ga = new GlideAjax('getUserData');
// sysparm_name is a reserved name, representing the Script Include function to be called
ga.addParam('sysparm_name', 'getUserSomeData');

// These sysparm_ parameters will be used by the Script Include
ga.addParam('sysparm_user_id', g_form.getValue("caller_id"));
ga.addParam('sysparm_user_field', 'manager');

// Calling a function makes this GlideAjax asynchronous
ga.getXML(getManager);

function getManager(response) {
  // Response is received as follows
  var answer = response.responseXML.documentElement.getAttribute("answer");
  if (answer) {
    g_form.addInfoMessage("Caller Manager is " + answer);
  } else {
    g_form.addInfoMessage("No Caller Manager found");
  }
}