Sort/Order List Field

David Casper
Tera Guru

I'm trying to figure out a way to order or sort the results for a list field. This field is auto populated in the background which is working, but the order of the results is the order that the script added the record to the field.

Since it's a reference field I know it's returning the sys_id so when I tried Array.sort which did not work. 

I can't see a way of controlling this at the dictionary level, so I'm guessing I would have to look at the value of the record in the list field? Maybe create a new array that stores the order based on the display value then add them from that array? 

Thanks

1 ACCEPTED SOLUTION

Hi David,

If you want it to be sorted each time the field is edited, the following should get you started as a Business Rule. This is an example on the watch list on the incident table, you'll need to alter it depending on the table your List field is pointing at and the display field for the table.

find_real_file.png

Script

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

	var watchlistArr = [];
	
	var userGR = new GlideRecord('sys_user');
	userGR.addQuery('sys_id', 'IN', current.getValue('watch_list'));
	userGR.orderBy('name');
	userGR.query();
	while(userGR.next())
		watchlistArr.push(userGR.getUniqueValue());
	
	current.setValue('watch_list', watchlistArr);

})(current, previous);

If my answer is correct / helpful, please remember to mark it as such so that others can see the information as easily as possible.

Callum

View solution in original post

7 REPLIES 7

Callum Ridley1
Tera Guru

Hi David,

The solution you suggest by calculating the order in a new array based on the display value of the referenced records, is the only solution to this as far as I know.

Callum

I was hoping my suspicion would not be confirmed! haha

Thanks for the prompt input.

 

Now to figure out how to actually implement that....any suggestions welcome 🙂

Hi David,

If you want it to be sorted each time the field is edited, the following should get you started as a Business Rule. This is an example on the watch list on the incident table, you'll need to alter it depending on the table your List field is pointing at and the display field for the table.

find_real_file.png

Script

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

	var watchlistArr = [];
	
	var userGR = new GlideRecord('sys_user');
	userGR.addQuery('sys_id', 'IN', current.getValue('watch_list'));
	userGR.orderBy('name');
	userGR.query();
	while(userGR.next())
		watchlistArr.push(userGR.getUniqueValue());
	
	current.setValue('watch_list', watchlistArr);

})(current, previous);

If my answer is correct / helpful, please remember to mark it as such so that others can see the information as easily as possible.

Callum