Filter users based on location

Revathi12
Tera Contributor

Hi Team,

 

Can anyone help me with the script on how to filter users based on the location selected. I have 2 fields one is location and other is user, if I select location I need to populate user based on the location selected.

 

Thanks

6 REPLIES 6

kkrushkov
Mega Sage

Hello @Revathi12,

What kind of script do you need exactly and what is the use case you need it for?

Revathi12
Tera Contributor

Use case :- I need to filter users based on the location selected. If I select a location I need to get the users which are mapped to that location.

Amit Gujarathi
Giga Sage
Giga Sage

HI @Revathi12 ,
I trust you are doing great.

Here's an example implementation:

Client Script :

function getUserBasedOnLocation() {
    var location = g_form.getValue('location'); // Get the selected location
    if (!location)
        return;

    var ga = new GlideAjax('UserFilterUtil'); // Create a GlideAjax object
    ga.addParam('sysparm_name', 'getUsersByLocation'); // Pass the name of the server-side function
    ga.addParam('location', location); // Pass the selected location
    ga.getXMLAnswer(populateUsers); // Make the asynchronous call and pass the callback function
}

function populateUsers(response) {
    var userField = g_form.getControl('user'); // Get the user field
    userField.innerHTML = response; // Populate the user field with the filtered users
}

 

Script Include

var UserFilterUtil = Class.create();
UserFilterUtil.prototype = Object.extendsObject(AbstractAjaxProcessor, {
    getUsersByLocation: function() {
        var location = this.getParameter('location'); // Get the selected location
        var userList = ''; // Initialize an empty string to store the filtered users

        // Query users based on the selected location
        var userGr = new GlideRecord('sys_user');
        userGr.addQuery('location', location);
        userGr.query();
        while (userGr.next()) {
            userList += '<option value="' + userGr.getValue('sys_id') + '">' + userGr.getValue('name') + '</option>'; // Build the HTML options for the user field
        }

        return userList; // Return the filtered users
    }
});

Was this answer helpful?


Please consider marking it correct or helpful.


Your feedback helps us improve!


Thank you!


Regards,


Amit Gujrathi



Hello, @Amit Gujarathi 
Well done on coming up with such a great solution.
What happens, I wonder, if the field is a reference rather than a list of options?