Dynamically retrieving the Labels of fields on the Current record

kevinclark-7EL
Tera Contributor

I've been struggling with this one for a little while now, and was hoping to find some help here.

I have a business rule on a table in a Scoped App which is running some functions to look at a related record to retrieve a comma separated list of field values, then use those field values elsewhere (to programatically create a text block for a child Incident record for example).

Current Record -> Related Configuration record (contains a comma separated list of field values called "additional_field_1")

//construct the text for all the display fields in the Subcategory Map string field

var displayFields = subCatMap.additional_field_1.toString();                             // Grab the Display Field from the Mapping table and split into array.

var fieldArray = displayFields.split(",");

for (var a=0; a< fieldArray.length; a++){                                                                     // use the field array to create a loop

var currentField = fieldArray[a];

fieldText += current.getElement('currentField').getLabel(); +": "+ current.getValue(currentField)+"\n";             // for each field in the loop, capture the Label and value with a Line Break

The line "current.getElement('currentField').getLabel();" doesn't get me what I want - I think at the moment it errors out.

I've tried "current.getLabel('currentField');' but this only gives me the label of the current record type - not the field that is named by my "currentField" string

Any idea how i might be able to ask ServiceNow to just give me current.currentField.getLabel() where currentField is dynamically set earlier in the loop?

6 REPLIES 6

Shawn Dowler
Tera Guru

I don't know of a better way to do this, but I know this works on the incident table for example:



current['number'].getLabel();



So from that you should be able to replace in line 6:



current.getElement('currentField').getLabel();



with:



current[currentField].getLabel();



Also, I'm not sure why you have a semicolon in line 6 after getLabel(), because that probably shouldn't be there.


Hey Shawn,



that's done the trick!   Thanks for your help!   I found reference to the square bracket syntax elsewhere, but I think I might have been trying to insert a "." before the brackets.   Good pick up on the semicolon - that was a cut paste error when I was putting the original question up.



In my testing I also found that adding the following lines worked, but your solution is far simpler.:


var currentFieldElement = current.getElement(currentField);


var currentFieldLabel = currentFieldElement.getLabel();



Cheers,


Kevin


That's interesting that is works when you break it up, but not when you try to put it together using dot notation. I'm glad you have a working solution.


Thanks!   Happy to get it working, thanks for the help.