Function required to find all childs of the parent on same table

ramandeepgarg6
Tera Expert

Hi Friends,

I have a "Department" table which contains a "Parent Department" field. See below screenshot. If I select department as 'A' then it should get all children as [A, B, C, BB1, BB2, CC1, CC2].

I have written below code but it is not working properly and it is not able to find all the departments. Could you please help?

getChildDepartment: function(dep, finalArr) {
var gr = new GlideRecord('u_cmn_department');
gr.addQuery('u_parent', dep);
gr.query();
while(gr.next()){
finalArr.push(gr.sys_id);
this._getChildDepartment(gr.sys_id, finalArr);
}
return finalArr;
},

Regards

Ramandeep

1 ACCEPTED SOLUTION

This is all you need.


I hope the table name i have put is correct 'cmn_department'


Try running the below script in Background Script



getChildDepartment('enter your department name here');


function getChildDepartment(dep)


{


var finalArr = [];


var gr = new GlideRecord('cmn_department');


gr.addQuery('u_parent.name', dep);


gr.query();


while(gr.next()){


finalArr.push(gr.sys_id);


while (gr.u_parent!='')


gs.addInfoMessage(gr.name);


        this.getChildDepartment(gr.name);


}



return finalArr;


}



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

View solution in original post

14 REPLIES 14

Hi Sanjiv,



This will return A, B, BB1 or A,B,BB2.



Regards


Ramandeep


Not sure why is that. I just removed an underscore. Try now. I am getting everything correctly



getChildDepartment: function(dep) {


var finalArr = [];


var gr = new GlideRecord('cmn_department');


gr.addQuery('u_parent', dep);


gr.query();


while(gr.next()){


finalArr.push(gr.sys_id);


if (gr.u_parent!='')


        this.getChildDepartment(gr.sys_id);


}


return finalArr;


},


find_real_file.png



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

Alikutty A
Tera Sage

How are you calling this function?



Thank You


Please Hit Like, Helpful or Correct depending on the impact of response


Hi Alikutty,



I am going to call this function from the "List of records" type module. I will use filter as "Department.sysID" IN "javascript: function".



Regards


Ramandeep


The function seemed ok but I wanted to know if you are passing an array into it



I would be calling this as



var arr= [];


getChildDepartment('parent_department_sys_id', arr);




Thank You


Please Hit Like, Helpful or Correct depending on the impact of response