Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Help with relating record to parent, and parents of parent

Farah5
Tera Contributor

I have a child record on a table called "Policy" that has a Parent field. If I add a record to a related list on the Policy table, I want that record to also be added to the related list of the Parent record. If that Parent record also has a Parent, then I want that related record to be added to the related list of that parent's parent, and so fourth. I basically want the record that is added to the related list to be related to the parent -> grandparent -> great grandparent and so fourth until it reaches a point where the Parent field is blank. 

 

My problem is that I'm just not sure how to script this in a way to have the script keep checking for Parents until there are no more parents. Right now, I have this script, but it only checks for the direct parent of the current record, and nothing further. It's checking for an update on a list field in the related record, and if it's updated, then it will also add the Parent record to that list. 

 

(function executeRule(current, previous /*null when async*/) {

	var childList = current.u_principle_assertion.split(',');
	var count = 0;
	var query = '';
	
	while(count < childList.length) {
		if(count == 0) {
			query += 'sys_id='+childList[count];
		} else {
			query += '^ORsys_id='+childList[count];
		}
		count++;
	}
	
	// sys_id=4a0d7c1e1bfdd554253e5538624bcb72^ORsys_id=984366b91bb51554253e5538624bcb83^u_parentISNOTEMPTY
	
	var policy = new GlideRecord('sn_compliance_policy');
	policy.addEncodedQuery(query+'^u_parentISNOTEMPTY');
	policy.query();
	
	while(policy.next()) {
		childList.push(policy.getValue('u_parent'));
	}
	
	current.u_principle_assertion = childList.join(',');

})(current, previous);

 

I hope this makes sense. Any help on figuring out how to related a record going up the parent chain would be great. 

 

1 REPLY 1

cynlink1
Tera Expert

@Farah5 - I am trying to solve for the same requirement. Were you able to get it working? If yes, would you mind sharing your final solution? Thanks!