How can I auto populate an employee ID based on the selected user?

nicolemccray
Tera Expert

I have a variable titled 'Facility Manager Name' (facility_manager_name) which is a reference field that allows the requester to look up and select a person.   I would like to auto populate the 'Employee Number' (emp_number) field based on the person selected.   I have tried the following Client Script, but I am doing something wrong:

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

var id = g_form.getValue('facility_manager_name');//replace 'u_first_field' with the name of your reference field.  

var user = new GlideRecord('sys_user');  

          user.addQuery('sys_id',id);  

          user.query();  

if ( user.next() ) {    

  g_form.setValue('emp_number', user.field_on_sys_user);  

}  

}

1 ACCEPTED SOLUTION

Replace g_form.setValue('emp_number', id.field_on_sys_user); with   g_form.setValue('emp_number', id.emp_number);


View solution in original post

15 REPLIES 15

Add below code in beginning of onChange function



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


return;


}


I must be adding in the wrong place?   Keep getting error.



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


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


var id = g_form.getReference('facility_manager_name');//replace 'u_first_field' with the name of your reference field.


  g_form.setValue('emp_number', id.emp_number);


  return;


}


}


Geoffrey2
ServiceNow Employee
ServiceNow Employee

You can do it without a Client Script by setting this as the default value in the Variable.


javascript:(function executeRule() {


  var user = new GlideRecord('sys_user');


  if (user.get(gs.getUserID())) {


      return user.employee_number;


  }


})();


Screen Shot 2016-09-01 at 11.56.26 PM.png


Geoffrey,


This script returns my own employee number, and not the employee number of the selected person.


Oh, sorry 😕 I didn't read the question properly.



Then you should be using a GlideAjax query: http://wiki.servicenow.com/index.php?title=GlideAjax