Sometimes we need to get the choices for a particular field in ServiceNow. If you’re like me, you just write yourself a method in a script include that calls the sys_choice table and passes the table name (name) and field (element).
I found that ServiceNow offers a more direct way to get this using the GlideChoiceListGenerator() API. So, if I wanted to get all the subcategory choices for the incident table, here’s a script that would get them.
NOTE: The GlideChoiceListGenerator() API is only valid in the global scope. So, if you’re trying to get choices for a scoped table, you could create a global-scoped script include to call the GlideChoiceListGenerator() API then in a scoped script include you could call the global-scoped script include. Here’s a script to get those subcategory choices. Run this script in scripts – background (global scope) to see how this works.
var tableName = "incident";
var field = "subcategory";
var choices = new GlideChoiceListGenerator(tableName, field);
var choiceList = choices.get();
var choicesListSize = choiceList.getSize();
var choiceOptions = [];
for (var i=0; i < choicesListSize; i++) {
var choiceLabel = choiceList.getChoice(i).getLabel();
var choiceValue = choiceList.getChoice(i).getValue();
var choiceObj = {
'label': choiceLabel,
'value': choiceValue
};
choiceOptions.push(choiceObj);
}
var message = "CHOICES FOR SUBCATEGORY:\n---------------------------------\n";
for (var x=0; x<choiceOptions.length; x++) {
var choiceObj = choiceOptions[x];
var choiceObjLabel = choiceObj['label'];
var choiceObjValue = choiceObj['value'];
message += "- LABEL: " + choiceObjLabel + ": " + choiceObjValue + "\n";
}
gs.info("\n\n" + message);