Retrieving Department for user in Client Script

robpickering
ServiceNow Employee
ServiceNow Employee

I'm using the following Catalog Client Script to attempt to retrieve the Department name:

function onChange(control, oldValue, newValue, isLoading) {

      if (isLoading || newValue == '') {

            return;

      }

      var newUser = g_form.getReference('requested_for',getDepartment);

}

function getDepartment(newUser){

      alert('The record is ' + newUser.department);

}

Where 'requested_for' is the name of the Catalog Variable on the form, which is a reference field for the sys_user table.

The issue is that the alert shows the *correct* sys_id for the user's department.   However, I need the name.

If I use:   newUser.department.name, it is returned as undefined.

If I use:   newUser.department.getDisplayValue(), it aborts the client script with an error.

I know I could get this working if I used a GlideAjax call and wrote a Script Include, but I was hoping to avoid that, as this seemed like that would be overkill for something as simple as this.

Thoughts?   I know, hope, I'm overlooking something simple.

-Rob

1 ACCEPTED SOLUTION

sumukh
Kilo Expert

Hi Robert,



You'll not get department name by getting reference from sys_user table. You'll only get the sys_id of department as that's what is actually stored at user level. Dot walking works in business rules but not at client script level. So either you'll have to do two getReference (one for user and second for department) or you can write a GlideAjax as you've mentioned in your post.



Hope this helps.



Thanks.


View solution in original post

4 REPLIES 4

sumukh
Kilo Expert

Hi Robert,



You'll not get department name by getting reference from sys_user table. You'll only get the sys_id of department as that's what is actually stored at user level. Dot walking works in business rules but not at client script level. So either you'll have to do two getReference (one for user and second for department) or you can write a GlideAjax as you've mentioned in your post.



Hope this helps.



Thanks.


robpickering
ServiceNow Employee
ServiceNow Employee

I was afraid of that, I'll probably modify a generic Utils Script Include that I have and write it as a GlideAjax call.


Thanks for pointing out that I couldn't dot-walk into the Department table to get the name, now I'll stop banging my head on the wall.



This will be more efficient than two getReference calls, though it does require the Script Include.


Yes. Script include will be a better way to do it.


edwin_munoz
Mega Guru

You can use this in a client script, although I think it would be better to use GlideAjax



var department = new GlideRecord("cmn_department");


department.get(sys_idOfDepartment);



department.name