Catalog client script to get department ID in service portal

lando321
Tera Contributor

Hello all,

Im trying to get the department ID on a catalog item, but i am having trouble getting this information to display in the service portal. 

Here is my form: 2 fields shown are in a variable set

lando321_0-1678477521198.png

I have tried a few catalog client scripts but none of them are working for me, upon searching i found that you have to use a callback function in the portal, but this callback function is still not working for me.

 

Catalog client script:

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }


    var user = g_form.getReference('name', callBack);

    function callBack(user) {


        g_form.setValue('department_code1', user.department.id);

    }
}

 

lando321_1-1678477979770.png

Could someone help give me some direction on this one?

1 ACCEPTED SOLUTION

Paul Deonarine3
Tera Expert

Can you try with below script, 

 

function onChange(control, oldValue, newValue, isLoading) {
  if (isLoading || newValue == '') {
    return;
  }

  // Get the user reference value from the "name" field
  var userRef = g_form.getValue('name');

  // Use the GlideRecord API to retrieve the user record and its associated department
  var userGr = new GlideRecord('sys_user');
  userGr.addQuery('sys_id', userRef);
  userGr.query(function(result) {
    if (result.next()) {
      var departmentRef = result.getValue('department');
      var departmentGr = new GlideRecord('cmn_department');
      departmentGr.addQuery('sys_id', departmentRef);
      departmentGr.query(function(result) {
        if (result.next()) {
          // Set the value of the "department_code1" field to the department ID
          g_form.setValue('department_code1', result.getValue('department_code'));
        }
      });
    }
  });
}

 

View solution in original post

10 REPLIES 10

Executing a GlideRecord within a Client Script is not supported nor considered best practice.  The solution is to use GlideAjax to call a Script Include when you need to access fields related to the reference field which cannot be done with getReference.  You'll need to know how to use this and troubleshoot it to get it to work even after the variable auto-populate feature in the Utah release for all of the other things you can do in a Script Include to return results for variables or as a reference qualifier.