This is a guest post by colleague – enjoy!

It’s difficult to set up a reference field to be dependent on another field if that reference doesn’t exist in the dictionary. An example of this is using Reference field variables in Wizards in ServiceNow. Servicenow does not offer the option to make one field dependent on another within a Wizard like you would with a normal dictionary entry but we can offer the same functionality using an advanced reference qualifier.

A simple way to do this is to change the reference qual field in ServiceNow to point to a script include which will return an encoded query for that reference field.

For example, below shows an example where we ensure the caller field is dependent on the company field on a form. This prevents users from selecting a contact which doesn’t belong to the company selected in the company field.

So we make the following Script Include:

Name: companyToUserRefQual

Active: True

Client Callable: True

//The function is called with the companySysID parameter which we pass in via the reference qual field
function companyToUserRefQual(companySysID) {
//Empty String to contain the filter we define later in the code. Leave this blank
var userFilter = ” “;
//In this instance, if the company field is blank, no sysid is passed through and I want this to simply return all active users for all companies with no qualifier.
if(companySysID == “”){
return ‘active=true’;
}
else{

//variable for the encoded query a full list of encoded string possibilities are available on the wiki
var enQry = ‘company=’;
enQry = enQry + companySysID;

//lookup on sys_user using the encoded query built earlier
var users = new GlideRecord(‘sys_user’);
users.addEncodedQuery(enQry);
users.query();

while(users.next()) {
if (userFilter.length > 0) {
//build a comma separated string of users if there is more than one
userFilter += (‘,’ + users.sys_id.toString());
}
else {
userFilter = users.sys_id.toString();

}

}
// return Users that meet our criteria, we use IN as the operator for lists of values. Any encoded query can be returned which will be applied to the reference field in our wizard.
return ‘sys_idIN’ + userFilter + “^active=true”;
}
}

Now the script include has been created, inside of the reference field you wish to apply this to, under the “Reference Qual” field, we use Javascript to run the script include and pass in the parameter of the company’s sys_id. In this case, as I am using these reference fields on a wizard, we can get this by using “current.variables.company_name”:

Reference Qual: javascript: companyToUserRefQual(current.variables.company_name)

 

 

2 Comments

  1. Stevie

    Was totally stuck until I read this, now back up and running.

    Reply
  2. eebest8

    “A round of applause for your article post.Really thank you! Keep writing.”

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *