logo

NJP

Get User Details based on the Logged in user/ User selected in Client Script

Import · Mar 03, 2020 · article

This article helps you get user data from the Server side on to your Client script.

1.Script Include Creation

Name: userDetailsUtil

API Name: global.userDetailsUtil (Auto populated by system)

Client Callable: Checked(True)

Active: Checked(True)

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

    getEmployeeDetails: function() {
        var userName = this.getParameter('sysparm_user');
        var user = new GlideRecord('sys_user');
        var result = { //Create an object to store the User data
            firstName: "",
            lastName: "",
            userID: "",
            location: "",
            manager: ""
        };
        if (user.get(userName)) {
            result.firstName = user.first_name.toString(); // toString is different from getDisplayValue
            result.lastName = user.last_name.toString(); // toString is different from getDisplayValue
            result.userID = user.user_name.toString(); // toString is different from getDisplayValue
            result.location = user.location.getDisplayValue(); //use getDisplayValue() value for reference fields
            result.manager = user.manager.getDisplayValue(); //use getDisplayValue() value for reference fields
        }
        return JSON.stringify(result);

    },
    type: 'userDetailsUtil'
});

image

2.Catalog Client Script creation

Name: Return User Details

Active: Checked (True)

UI Type: ALL

Type: OnChange

Variable Name: Logged in user Variable.

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    var user_id = g_form.getValue('requested_for');
    var ga = new GlideAjax('userDetailsUtil');//name of script include
    ga.addParam('sysparm_name', 'getEmployeeDetails');//name of function on script include
    ga.addParam('sysparm_user', user_id);//name of field on form triggering call
    ga.getXML(EmployeeDetailsLookup); // Always try to use asynchronous call
}

// Callback function to process the response returned from the server
function EmployeeDetailsLookup(response) {
    var answer = response.responseXML.documentElement.getAttribute("answer");
    var result = JSON.parse(answer);
    g_form.setValue('first_name',result.firstName);
    g_form.setValue('last_name',result.lastName);
    g_form.setValue('user_name',result.userID);
    g_form.setValue('location',result.location);
    g_form.setValue('manager',result.manager);
}

image

If this article helped in you in any which way, please mark it as helpful/bookmark it.

-Best Regards

Prateek kumar

View original source

https://www.servicenow.com/community/developer-articles/get-user-details-based-on-the-logged-in-user-user-selected-in/ta-p/2321140