logo

NJP

How To: Dynamic data in UIB Dropdown component

Import · May 06, 2022 · article

How to use dynamic data options in your dropdown component (and other components)

The dropdown component lets you use data binding from a data resource(data broker), however, this resource output is probably not in the correct format which would result in 'blank' results in the dropdown. To fix this, you can write a simple script to create your options and have them display correctly.

Step 1. Create your look up records data resource (the options you want to show)

You will want to use the "look up records" data resource.

Click the data resource button to open up the data resource pane.

image

Click 'add'

Select 'Global', then select "Look Up Records", then click "add" on the far right.

(you may have to scroll down to see the add button.)

image

Now that you have added it, go back to the data resource pane, and click on your new resource. Mine is called "Look Up Records 1" - though you should give it a more meaningful name.

image

Enter the table you want to pull records from in the "table" field.

Enter at Field you want to display, and the sys id field. (this is important later)

Move on to step 2.

Step 2. Add your script to the dropdown component 'items' field

Select your dropdown component, either from the content pane or by clicking on it in the page.

Select the "Config" panel and scroll down to the "items" field.

Select the script button "</>"

image

Now select the 'Expand editor' button in the top right to have more room.

image

Now that we can see better, replace the script with this script below.

Replace replace 'look_up_records_1' with your data resource name from above, in all instances of 'api.data.look_up_records_1".

Replace the field name 'name' with your field name. Leave sys_id as it is.

Important: Leave the object properties the same (don't change 'id' or 'label')

Click apply, click save in the top right of UI Builder.

Open your page to see your new dropdown!

/**
* @param {params} params
* @param {api} params.api
* @param {any} params.imports
*/
function evaluateProperty({api}) {
var arr = [];

for(var i = 0; i<api.data.look_up_records_1.results.length; i++)
{
var myObj = {};
  myObj.id = api.data.look_up_records_1.results[i].sys_id.value;
myObj.label = api.data.look_up_records_1.results[i].name.value;

arr.push(myObj);

}
return arr;
}

View original source

https://www.servicenow.com/community/developer-articles/how-to-dynamic-data-in-uib-dropdown-component/ta-p/2305734