Get list of choice field values with display values

Pradnya6
Giga Contributor

From a element descriptor I can get the dictionary elements of the field. I am using following code for the same.
var gr = new GlideRecord('cmdb_ci_ip_address');
gs.setLimit(1);
gr.query();
if (gr.next())
{
var choices = gr.getElement('ip_version').getChoices();
// need list of choice display values
}

Is there OOB function to get the display values list of a choice field?

5 REPLIES 5

DaleHurtt
Kilo Contributor

The problem is that the documentation for getChoices () says that it returns an array list of choices. The reality is that it returns the SELECTED choice value as a GlideElement. You can prove this with:

gs.addInfoMessage (gr.getElement('ip_version').getChoices() instanceof GlideElement);

If that is what you are looking for, then gr.getElement('ip_version').getChoices().toString () will return a string of the choice value you selected. If you are looking for the label of that choice use gr.getElement('ip_version').getChoices().getChoiceValue () or .getDisplayValue ().

If you are looking for the original list of values/labels that are available in the choice list, you are going to have to tap the Choice table (sys_choice) and match on the table and element fields.

I hope that helps.


DaleHurtt
Kilo Contributor

You don't need to do the query to obtain the GlideRecord. You can simply use current, which is a global of the current GlideRecord. Saves a lot of steps and a query on the database.

Now if you end up trying to find the definition of the choice list, you WILL have to use the method you described, but you will be hitting the sys_choice table instead (unless the choices are coming from yet another table, but that is a different use case.)


Not applicable

Have a look at the ChoiceList() script include.

You'll need to loop through your list of choices, that you've already got, but its getLabel(value) method will return the label for value, for the current session language.

NB. You don't need to retrieve a record in order to call getChoices(), you can use newRecord() instead.



var gr = new GlideRecord(recordType);
gr.newRecord();
var choiceList = j2js(gr.getElement(choiceField).getChoices());
var cl = new ChoiceList(recordType, choiceField);
for (var i=0; i < choiceList.length; i++ ) {
gs.print(choiceList<i> + ', ' + cl.getLabel(choiceList<i>));
}


(the j2js() function is useful here because for some inexplicable reason the javascript getChoices() method was written to return a Java ArrayList.)


avin3
Kilo Contributor

Thank you for this solution. j2js function is what changed the game. It was very helpful.