Creating Choice Values via Script

Have you ever found yourself performing the tedious activity of manually creating values for a sys_choice field? When only a handful of values need to be created, the process is not much of a burden, but having to create 20, 30, or more values can be a time consuming bear of a process.

Below you will find a script by which sys_choice records can be generated quickly and with less effort.

The Script

function createChoices(table, element, list, startSequence, dependentVal){ var values = list.split(","); var seq = (startSequence ? startSequence : 100); var dep = (dependentVal ? dependentVal : ""); for(var i = 0; i < values.length; i++){ var grChoice = new GlideRecord("sys_choice"); grChoice.initialize(); grChoice.name = table; grChoice.element = element; grChoice.sequence = seq grChoice.dependent_value = dep; grChoice.label = values[i]; grChoice.value = convertToValue(values[i]); grChoice.insert(); seq += 100; } } function convertToValue(input){ var output = ""; var regex = /\w+/; var lowText = input.toLowerCase(); var split = lowText.split(/[ \W]/); for(var i = 0; i < split.length; i++){ if(regex.test(split[i])){ output += split[i]; } if((i + 1) != split.length){ output += "_"; } } while(output.indexOf("__") != -1){ output = output.replace("__", "_"); } while(output.lastIndexOf("_") == (output.length - 1)){ output = output.substring(0, (output.length - 1)); } return output; }

How does it work?

Inputs:

table – Name of the table the choices belong to

element – Name of the field the choices belong to

list – Comma-separated list of labels, each representing a different choice value

startSequence (optional) – The first index to be used for the sequence values of the choices (defaults to 100, auto-increments by 100)

dependentValue (optional) – The value to populate the dependent value field with (defaults to empty)

The script takes the above parameters. The first three are required, and the last two are optional.

Note: The “list” input must be a comma-separated list of choice labels. The current version of the script cannot accommodate values that contain commas. Also, it’s worth acknowledging that, for this script to work, the list of choices that need to be created still must be converted to a comma-separated list, which takes some time, but this is typically easier than manual entry of the choices. For moderately long lists, Excel can be used to convert a newline-delimited list into comma-separated values, and, for lengthy lists, it may be advisable to utilize ServiceNow’s transform map functionality instead of this method.

The “convertToValue” script creates a lower-case, underscore-laden value for the choice’s “value” field, derived from the label, stripping out any non-alphanumeric characters. For example, “Test Label – More Text” would be converted to “test_label_more_text.”