Auto populate the location based on user's location.

Deepak Shaerma
Kilo Sage

Hi Community

I need to Auto populate the custom "Location field (Type : choice)"  based on logged in user's location. If required user can change it also manually.  How to do this. I attached a screenshot of the incident form. this needs to done in incident form.

3 REPLIES 3

jaheerhattiwale
Mega Sage
Mega Sage

@Deepak Shaerma 

Please create an onload client script and write a GlideAjax in it.

Create a client callable script include which is needed for GlideAjax.

GlideRecord on user table and query user table using logged in users sys id using gs.getUserID().

Return the location of logged in user from script include.

In client script, in GlideAjax callback function set the custom location field.

 

Link to GlideAjax doc: https://docs.servicenow.com/en-US/bundle/tokyo-application-development/page/script/ajax/topic/p_AJAX...

 

Note: in documentation you will get a sample code as well

 

Please mark as correct answer if this solves your issue.

Please mark the answer as correct or helpful based on impact
ServiceNow Community Rising Star, Class of 2023

akash27
Tera Contributor

You need 2 components:
1. onLoad client script
- here you will have to write the code in isLoading part as well.
2. Script Include
- You can return this to the client script from your include: gs.getUser().getLocation();

OR
You can do this via Display Business rule 
and use "gs.getUser().getLocation();".
In display business rule you can add a condition check
if location is not empty OR the location is "gs.getUser().getLocation()", then don't auto populate

Gunjan Kiratkar
Kilo Patron
Kilo Patron

Hi @Deepak Shaerma ,

I will recommend you to go with Business rule. Because onload client script will change the location everytime when form loaded. It may be any itil user or agent.

So better to go with Before insert Business rule as below :-

GunjanKiratkar_0-1670587713744.png

 

(function executeRule(current, previous /*null when async*/ ) {

    // Add your code here
    var userLocation = gs.getUser().getRecord().getDisplayValue("location"); 
    var gr = new GlideRecord("sys_choice");
    gr.addEncodedQuery("name=incident^element=u_location^label="+userLocation); //Change your field backend value in place of "u_location".
    gr.query();
    while (gr.next()) {
		current.u_location=gr.value;
	
    }

})(current, previous);

 


Please Mark My Response as Correct/Helpful based on Impact
Regards,
Gunjan Kiratkar
2X ServiceNow MVP
Community Rising Star 2022
Youtube : ServiceNow Guy