- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
01-30-2020 10:36 AM
Hi ServiceNow Community Developers,
By default if you use "orderby" in a choice field the sort is done by the actual value of that choice field as defined in the choice table. There are times where the choice value is a numeric / integer but the actual choice Label is characters. Right now I have a requirement whereby I have to returned the results sorted by category however since category is a choice field the query is returning results that are sorted by the value of the category field. The desired behavior is to sort the query results based on the display value of the category field which is the Label field on the choice table.
Would you please advise if there is a way to use the display value of a choice field rather than the actual value of a choice field when sorting your query results using a choice field.
I tried to use the display value using the script below which I am running as a background script however I am not getting the correct results.
sortByChoiceField();
function sortByChoiceField() {
var gr = new GlideRecord("sn_customerservice_case");
gr.addActiveQuery();
gr.orderBy("category.getDisplayValue()");
gr.query();
while (gr.next()) {
gs.print ("category value " + gr.category + " category name " + gr.category.getDisplayValue());
}
}
Kindly advise.
Thanks,
Johannes
Solved! Go to Solution.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
02-08-2020 09:30 AM
Hey Guys,
I figured it out. This is what i did: read the data with a GlideRecord and add it into an array. When I add the data into an array for choice fields I add the display values. Once I have read all the data I then sort the array using the display value of whatever choice field i want to sort with e.g. category in this case. I then return the sorted array and that is working perfectly as expected.
Here is a sample of my code for the sorting part:
Thanks,
Johannes

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
01-30-2020 12:56 PM
Your gliderecord isn't on the sys_choice table, but if it were, you could us orderBy('label') to sort by the label vs the value.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
02-08-2020 09:30 AM
Hey Guys,
I figured it out. This is what i did: read the data with a GlideRecord and add it into an array. When I add the data into an array for choice fields I add the display values. Once I have read all the data I then sort the array using the display value of whatever choice field i want to sort with e.g. category in this case. I then return the sorted array and that is working perfectly as expected.
Here is a sample of my code for the sorting part:
Thanks,
Johannes