Get the topmost parent from a parent child relationship (business unit)

anirban300
Kilo Guru

Hello All,

 

I want to fetch the topmost parent business unit and set it in the user table. I am stuck in between with the below after insert/update business rule.

 

1. In the user table there is a filed called "Department". 

2. Every "Department" has a "Business Unit" associated with it.

3. Every "Business Unit" has a parent "Business Unit" set in the "Parent" field.

4. We have created a custom string field "Business Unit" on the user table.

5. On change of department, the topmost parent "Business Unit" should be set.

 

I have written the below after business unit on the user table, but it's limited to fetch only the first parent. Can someone help me in fetching the topmost parent from the business unit table?

 

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

var gr = new GlideRecord('cmn_department');
gr.addQuery('sys_id', current.u_d);
gr.query();
while (gr.next()) {
var bu = gr.business_unit;
var grb = new GlideRecord('business_unit');
grb.addQuery('sys_id', bu);
grb.query();
while (grb.next()) {
var parent = grb.parent;
current.u_business_unit = prent.name;
}
}
current.update();
})(current, previous);

1 ACCEPTED SOLUTION

AnubhavRitolia
Mega Sage
Mega Sage

Hi @anirban300 

 

Please find updated code below:

 

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

current.u_business_unit = getBUParent(current.u_d.bussiness_unit);
current.update();

})(current, previous);

function getBUParent(bu)
{
var grb = new GlideRecord('business_unit');
grb.addQuery('sys_id', bu);
grb.query();
if (grb.next()) {
  if (!grb.parent) {
    return grb.sys_id;
  } else {
    return getBUParent(grb.parent);
  }
}

 

 

Please mark this as correct answer and helpful if it resolved, or mark this helpful if this help you to reach towards solution.

Thanks
Anubhav Ritolia
ServiceNow Rising Star 2023

View solution in original post

6 REPLIES 6

Community Alums
Not applicable

@AnubhavRitolia This is returning Undefined value

SanjivMeher
Kilo Patron
Kilo Patron

Please have the courtesy to mark other answers as helpful at least. The script, which was marked answered was the same script I posted was just copied and edited. And the edited script also returns sysid instead of business unit while you have a string field. How did it work for you?


Please mark this response as correct or helpful if it assisted you with your question.