Script to loop through parent locations

Rudi2
Giga Guru

Hi Guys


Can anyone maybe assist or have tried looping through the user's location's parent fields until a match is found?


We are going to change the location structure to maybe have 3 to 4 levels of parent values and we want to match a location field on a form to see if that selected location is in the user's location structure.




Location 1's parent is location 2 and its parent is location 3.


On the form they selected location 3, so I want people with location 1 to have access as well.


I hope it makes sense!


Regards

1 REPLY 1

Patrick DeCarl1
ServiceNow Employee
ServiceNow Employee

Hi, below script is example of looping through the location parent record and getting all the child. If you want to go the other way just change the flow. 

 

 

//the call
var locationArr = [];
				this._loadLocationParentUsers(current.u_crisis_event.u_primary_location.sys_id, 'name', locationArr, current, 100);


_loadLocationParentUsers: function(id, orderby, arr, current, i){
							//gs.info('crisisMgmtUtils -- _loadLocationParentUsers -- Running '+id);
							if(i == 0){
								return;
							}
							var tree = null;
							var myGR = new GlideRecord('cmn_location');
							if (myGR.get(id)) {
								this._getUsers(myGR.getUniqueValue(), current);
								arr.push(id);
								var childrenGR = new GlideRecord('cmn_location');
								childrenGR.addQuery('parent', id);
								if (orderby && orderby.length) {
									childrenGR.orderBy(orderby);
								}
								childrenGR.query();
								while (childrenGR.next()) {
									this._loadLocationParentUsers(childrenGR.getUniqueValue(), orderby, arr, current, i-1);
								}
							}
						},