How do I autopopulate the Location field on my Catalog Item, depending Company the User is a part of

patrykprejs
Tera Contributor

Hi All,

 

I am trying to autopopulate the Location field on my Catalog item, the dependency is the User ref field and it should be dependant on what Company the User is a part of.

 

For Example:

 

Name of User: User 1 (User 1 is a part of Company A)

Location: Location 6 (Location 6 is selected because User 1 is part of Company A, if not then clear the value)

 

Does anyone know how I can accomplish this?

I have tried using a SI and a Client Script but had no luck, please see the examples below:

 

Script Include:

var UserDetailsUtil = Class.create();
UserDetailsUtil.prototype = Object.extendsObject(AbstractAjaxProcessor, {

    getUserCompany: function() {
        var userSysId = this.getParameter('sys_id');
        var userRecord = new GlideRecord('sys_user');

        if (userRecord.get(userSysId)) {
            var companyName = userRecord.company.name;
            return companyName;
        }
        return '';
    }

});

 
Catalog Client Script:

function onChange(control, oldValue, newValue, isLoading) {
    // Ensure the script runs only when the form is not loading
    if (isLoading || newValue == '') {
        return;
    }

    // Get the sys_id of the user selected
    var userSysId = g_form.getValue('name_of_user');

    // If no user is selected, clear the 'location_to_send_to' field
    if (!userSysId) {
        g_form.clearValue('location_to_send_to');
        return;
    }

    // GlideAjax call to get user information
    var ga = new GlideAjax('UserDetailsUtil'); // GlideAjax class to call Script Include
    ga.addParam('sys_id', userSysId); // Send user sys_id
    ga.getXMLAnswer(function(response) {
        var userCompany = response;

        // Check if the user belongs to 'CompanyA'
        if (userCompany == 'CompanyA') {
            // Set the 'location_to_send_to' field to 'Location6'
            g_form.setValue('location_to_send_to', 'ab2e946b833302109af46060ceaad3b0', 'Location6');
        } else {
            // Clear the 'location_to_send_to' field if the user is not part of 'CompanyA'
            g_form.clearValue('location_to_send_to');
        }
    });
}

 

Thanks for any help in advance.

5 REPLIES 5

Hello,

Ok. I would recommend reviewing if GlideAjax is needed to set the location within the actual client (with the user right there), or if this is something that could instead, be handled via Flow Designer (and using a decision table for example), instead. Up to you on when you need to do this, but if in client, then yes, review your GlideAjax and as mentioned above, I gave a cheat sheet on how to set it up so you can review that for guidance.


Please consider marking my reply as Helpful and/or Accept Solution, if applicable. Thanks!