When you have sibling records, i.e. records that are somehow related to each other but that don’t have a parent, one way to relate them is with a list field. The below script can be put into a business rule on the table, triggered to run when the list field changes. This script goes to the related records and syncs the list field (here the list field is u_related_records).
Note that this only works for simple relationships where two or more records are related to each other but not with any other records. Set the filter in the list field to u_related_recordsISEMPTY to avoid having multiple relationships created.
(function executeRule(current, previous /*null when async*/ ) {
//Syncs the Linked Interdisciplinary PDs field for all related records.
//put the previous values into an array
var prevArr = [];
if (previous.getValue('u_linked_records')) {
prevArr = previous.getValue('u_linked_records').split(',');
}
//put the current values into an array
var interArr = [];
if (current.getValue('u_linked_records')) {
interArr = current.getValue('u_linked_records').split(',');
}
//check if there were any values removed
removedValues = [];
for (var i in prevArr) {
if (interArr.indexOf(prevArr[i]) == -1) {
removedValues.push(prevArr[i]);
}
}
//if there were values removed, clear the field of the records that were removed
if (removedValues.length > 0) {
remGR = new GlideRecord('sn_hr_core_position');
remGR.addQuery('sys_id', 'IN', removedValues.toString());
remGR.query();
while (remGR.next()) {
remGR.setValue('u_linked_records', '');
remGR.setWorkflow(false);
remGR.update();
}
}
//The below section updates the other records in the list field (the sibling records) such that the Linked Interdisciplinary PDs field is synced for all the records.
//add the current record to the currant value array
interArr.push(current.getUniqueValue());
interGR = new GlideRecord('sn_hr_core_position');
interGR.addQuery('sys_id', 'IN', current.getValue('u_linked_records'));
interGR.query();
while (interGR.next()) {
//filter the array to remove the sys_id of the record we are updating.
var filteredArr = interArr.filter(function(sys_id) {
return sys_id != interGR.getUniqueValue();
});
//update the sibling record
interGR.setValue('u_linked_records', filteredArr.toString());
interGR.setWorkflow(false);
interGR.update();
}
})(current, previous);
