How To Populate Choice Dynamically from API Response?

aryanjain27
Tera Contributor

Hi,

I have a api that returns list of names and unique ids in the format:

 

{
"data": [
{
"name": "Apple",
"uid": "ap"
},
{
"name": "Banana",
"uid": "bn"
}
]
}

 

 

I am trying to create a choice field in the catalog item that can present the names of these as dropdown option And in the backend uids should be used.
There's another accounts drop down field and the value selected there is appended as parameter to the API. So The options available depends on the account selected.
I use GlideAjax and I have a rest api "get" method I know its able to hit the api because I can see the logs. But when I try to get these values it wont work. Note: It can take few seconds to get the values (around 4-5 sec) from API. And there can be 100s of value

Whats the best way to implement this? With least time consuming when selecting accounts.

Script Includes:

 

getNamesAndUids: function() {

        // Get the API and Secret Key
        var apiAndSecretKey = JSON.parse(this.getAPIandSecretKey());
        var api = apiAndSecretKey.api;
        var key = apiAndSecretKey.key;

        // Initialize the REST request
        var request = new sn_ws.RESTMessageV2();

        // Set the API endpoint
        request.setEndpoint(api);
        request.setHttpMethod('GET');

        // Set the API Key
        request.setRequestHeader('x-api-key', key);
        
        var response = request.execute();
        var responseBody = response.getBody();
        var parsedResponse = JSON.parse(responseBody);

        // Return the names and Uids
        return {
            data: parsedResponse.data
        };
    }

 

 

client-script:

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue === '') {
        return;
    }

    var ga = new GlideAjax('names');
    ga.addParam('sysparm_name','getNamesAndUids');
    ga.addParam('sysparm_accountSysId', newValue);
    ga.getXMLAnswer(function(answer){

	var response = JSON.parse(answer);
	data = response.data;

        var nameField = g_form.getField('names_dropdown'); 
        g_form.clearOptions('names_dropdown');
        data.forEach(function(name) {
            g_form.addOption('names_dropdown', name.name, name.uid);
        });

   });
}
1 REPLY 1

Gangadhar Ravi
Giga Sage
Giga Sage

You need to use Remote table for this scenario. Please see docs .

 

https://docs.servicenow.com/bundle/washingtondc-servicenow-platform/page/administer/remote-tables/co...

 

Please mark my answer correct and helpful if this works for you.