Set reference fields based on string
Import
·
Mar 08, 2022
·
article
This examples is used to set the location of a CI based on a few characters available in the name.
Type: before Business Rule
(function executeRule(current, previous /*null when async*/) {
//Set two properties which has a 1v1 relation. 1 for string and the other for the sys_id of the record
var prpt1 = gs.getProperty('ci.location.string').toString();// This containts the string text that needs to be compared
var prpt2 = gs.getProperty('ci.location.value').toString(); // This contains the sysids of the related record
var str = prpt1.split(',');
var location = prpt2.split(',');
var name = current.name.toLowerCase().toString();
var mloc = []; //Locations matched in the name
var ploc = []; //Position of locations matched in the name
var floc = []; //First location in name
var sloc = ''; //First location in name as string
//Get array of locations matched
for(var i = 0; i < str.length; i++){
if(name.indexOf(str[i]) > -1){
mloc.push(str[i]);
ploc.push(name.indexOf(str[i]));
}
}
//End script if no locations found
if(ploc.length == 0) {
current.location = '';
return;
}
//Get first location if 2 locations found
if(ploc.length == 2) {
if(ploc[1] < ploc[0]){
floc.push(mloc[1]);
} else {
floc.push(mloc[0]);
}
} else {
floc.push(mloc[0]);
}
sloc = floc.toString();
var pos = str.indexOf(sloc); //Position in str array - Line 6
var loc = location[pos]; //Get value in same position in location array - Line 7
current.location = loc;
})(current, previous);
View original source
https://www.servicenow.com/community/developer-articles/set-reference-fields-based-on-string/ta-p/2322635