Show current logged in user in first in list then show remaning users inalphabetical order

ArunaTunga
Tera Contributor

Hello Everyone,

 

In service Catalog form one field called Requested for, in that first name should be current logged in User, remaining names should show in alphabetical order.

ex: if current logged in user is Admin then that field should look like

System Administrator

Abel Tutor

B

C

...

names in alphabetical order.

 

don't want use default value.

4 REPLIES 4

GlideFather
Tera Patron

Hi @ArunaTunga,

 

this will be difficult to impossible to achieve... but what you can try is to set the logics on [sys_ui_recent_selection] table where you can see these values from reference fields per user, table and fields:

 

https://yourinstance.service-now.com/sys_ui_recent_selection_list.do

Screenshot 2026-03-09 at 22.30.12.png

This is for particular users, not sure if you can use this as a global settings... These are the recent selections per user, so it will vary for most of the profiles. Try to play around with these values, perhaps having a record with empty user would be then applicable for all users (similar to User Preferences) but you must test and validate this... but something like a scratchpad in an onLoad script (to capture logged in user) and glideAjax to update the table with the logged in user in the top...

 

Another thing would be an attribute in that field's system dictionary. As you want a logged in user to be suggested in the top, then I am worried you will need to do some serious manipulations which I wouldn't recommend you... 

 

When I think about it, perhaps the easiest way would be to set the currently logged in person to the Requested for field and if somebody wants to change it, then they can update it.

What do you say?

_____
100 % GlideFather experience and 0 % generative AI

ArunaTunga
Tera Contributor

Hi Glide Father,

 

I have tried some script it was working fine in BG script but not working in script include+reference qualifier, if you find any mistake in my code please let me know.

 

Script Includes:

var GetCurrentLoggedInUserFirstInList = Class.create();
GetCurrentLoggedInUserFirstInList.prototype = {
    initialize: function() {
    },
    getLoggedinUser:function(){
        var currentUser = gs.getUserID();
        var users =[];
        var gr = new GlideRecord('sys_user');
        gr.addActiveQuery();
        gr.orderBy('name');
        gr.query();
        while(gr.next()){
            if(gr.sys_id!=currentUser){
                users.push(gr.sys_id.toString());
            }
        }
        //putting current logged in user in first in list
        users.unshift(currentUser);
        return 'sys_idIN'+users.join(',');
    },
    type: 'GetCurrentLoggedInUserFirstInList'
};
 
Advanced Reference Qualifier(requested for field):
javascript: new GetCurrentLoggedInUserFirstInList().getLoggedinUser();
Background script:

var currentUser = gs.getUserID();
var users = [];
var gr = new GlideRecord('sys_user');
gr.addActiveQuery();
gr.orderBy('name');
gr.query();
while(gr.next()){
    if(gr.sys_id!=currentUser){
        users.push(gr.sys_id.toString());
    }
}
users.unshift(currentUser);
gs.print(users.join(','));
it was printing sys_id for current logged in user on top but not in script includes.
 

 

The directives used by the variable widgets in the portal use the angular processor com.glide.ui.ng.AngularProcessor (nav_to.do?uri=sys_processor.do?sys_id=87f7ee0147133000ba13a5554ee49005) to interact with the backend. You can observe this from the network tab on your browser devtools while you interact with the requested for variable for example.

 

It looks like below, payload has things like the table and the query used as an encoded query string

Request URL .../angular.do?sysparm_type=sp_ref_list_data&sysparm_cancelable=true
Request Method POST

 

We don't have much control over how the directives work and zero control over how the processor works. The order the results are returned in are baked in. The widget also lazy loads the results so you'll get more results as you scroll down on the dropdown.

 

I don't recommend this necessarily but it is possible to decorate the oob directives to alter functionality. Here is a demonstration for your requirements. Using a decorator i replaced the filterresults function in the controller of the directive. The new function just pushes the logged in user choice to the top. Of course if the user is not in the first page it will not work until the results/cached array contains the user so it would need to be implemented differently. 

// added to catalog item widget as a uiscript js include
angular.module('sn.$sp').config(function ($provide) {
	$provide.decorator('spReferenceElementDirective', function ($delegate, $injector) {
		var directive = $delegate[0];
		var original = directive.controller;

		directive.controller = ['$scope', '$rootScope', function ($scope, $rootScope) {
			var ctrlInstance = $injector.instantiate(original, {
				$scope: $scope,
				$rootScope: $rootScope
			});

			$scope.pageSize = NOW.ac_max_search_matches;
			ctrlInstance.filterResults = function (data, page) {
				var arr = (data && data.data && Array.isArray(data.data.items))
					? data.data.items
					: [];

				var uid = (window.NOW && NOW.user_id) ? NOW.user_id : null;

				if (uid && arr.length) {
					var index = arr.findIndex(function (item) {
						console.log(item.sys_id)
						return item.sys_id === uid;
					});
					if (index > 0) {
						var [match] = arr.splice(index, 1);
						arr.unshift(match);
					}
				}

				console.log(arr[0])
				return {
					results: arr,
					more: (page * $scope.pageSize < data.data.total)
				};
			};
			return ctrlInstance;
		}]
		return $delegate;
	})
})

 In action:

123213.png

Not quite sure what your requirements are here but you could just add a custom variable with an "add me" button that adds the current user to the requested for.

Ankur Bawiskar
Tera Patron

@ArunaTunga 

I will recommend not doing this requirement as this involves heavy customization even if it's feasible to implement.

Please stick to OOTB to avoid technical debt

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

Regards,
Ankur
Certified Technical Architect  ||  10x ServiceNow MVP  ||  ServiceNow Community Leader