helpers - UI Builder
The helpers API provides general functionality that is common across page scripts, eliminating the need to write scripts for simple functionality such as opening and closing a modal.
- component property value scripts
- component visibility scripts
- event payload scripts
- UX client script includes
helpers - helpers.modal.close(String modalId)
Closes the specified modal on the current page.
| Name | Type | Description |
|---|---|---|
| modalId | String | Modal component ID of the modal to close. Component IDs are auto generated when a component is dragged and dropped on the UI Builder stage. You can locate the ID on the property page. |
| Type | Description |
|---|---|
| None |
This example shows closing a modal with a component ID that ends with
alert-modal.
function handler({api, event, imports, helpers}) {
helpers.modal.close("[component-id$='alert_modal']")
}
helpers - helpers.modal.open(String modalId, Object options)
Opens the specified modal on the current page.
You can only display one modal at a time within a page. If a modal is currently open, and you call this method, the existing modal is hidden and the new modal appears.
| Name | Type | Description |
|---|---|---|
| modalId | String | Component ID of the modal to open. Component IDs are auto generated when a component is dragged and dropped on the UI Builder stage. You can locate the ID on the property page. |
| options | Object | Optional. |
| options.content | String | Text content for the modal. |
| options.contentFullWidth | Boolean | Flag that indicates whether to remove the horizontal padding around the body of
the modal in order to fit wider content. Valid values:
Default: false |
| options.headerLabel | String | Text content for the modal header. |
| options.size | String | Size of the modal container. Most sizes automatically expand to fill the
viewport when the screen size is small. Valid values:
Default: sm |
| Type | Description |
|---|---|
| None |
This example shows opening a modal with ca omponent ID that ends with
alert-modal.
function handler({api, event, imports, helpers}) {
helpers.modal.open("[component-id$='alert_modal']")
}
helpers - helpers.navigate.setRouteParams(Object params)
Passes the specified parameters down to other components on the same page.
Use this method in any page component that wants to add a parameter in a URL. You may want
to add a parameter to a URL when another component needs to know the current value of that
parameter when it changes, so it can react to it. For example, use this method to pass the
selectedIndex of a tab component so it reflected in the URL to give focus
to that tab.
| Name | Type | Description |
|---|---|---|
| params | Object | Key-value pairs of optional parameters to pass to other components. This must be a plain, flat object with only primitive values. Array or object references are ignored and not added to the URL. All specified keys must be part of the optional parameters in the route configuration or they are also ignored. For additional information on optional parameters, see Create a page in UI Builder. |
| Type | Description |
|---|---|
| None |
This code example shows how to append the URL params/selected-tab-index/2.
Note that the parameter in the actual URL is changed from camel case to snake case, so
selectedTabIndex becomes selected-tab-index.
function handler({api, event, helpers, imports}) {
helpers.navigate.setRouteParams({'params': {'selectedTabIndex': 2}});
}
helpers - helpers.navigate.to(String route, Object fields, Object params, Boolean redirect, Boolean passiveNavigation, String targetRoute)
Navigates from one screen to another based on the specified route and field information. URL changes and the respective screen loads are observed.
| Name | Type | Description |
|---|---|---|
| route | String | Name of the route. Must be a valid entry from UX App Routes
(sys_ux_app_route.list). This value is reflected in the URL, and the URL is created
based on the route, fields, and
optionalParams column values:
/<route>/<field1Value>/{<field2Value>/params/<optionalParamKey1>/<optionalParamValue1>/<optionalParamKey2>/<optionalParamValue2>
For
example:
|
| fields | Object | Optional. Key-value pairs of required parameters. For example: 'fields'
: {'table': 'incident', 'sysId': '12345'}. |
| params | Object | Optional. Key-value pairs of optional parameters. For example: 'params'
: {'selectedTabIndex': 4}. |
| redirect | Boolean | Flag that indicates whether to remove the latest history entry from the browser
history. For example, if you navigate to sites A, B and then C. If
redirect is set to true while navigating to
C, the history entry for B is removed. The browser history only shows only A and
C.Valid values:
Default: false |
| passiveNavigation | Boolean | Flag that indicates whether to perform background navigation. Background
navigation is when a page is opened but it is not active or shown. For example,
opening an inactive tab for the page, but it is not visible but loaded in the
background. Valid values:
Default: false |
| targetRoute | String or Object | Sub navigation to a drill-down, deep-link, or sub-tab. If set to
current, the current route does a sub-navigation under the
current URL. For example, if
The following URL is generated:
注: targetRoute
can be either a string such as 'current' or an object, such as
navigation NAV_ITEM_SELECTED payload. |
| Type | Description |
|---|---|
| None |
This example shows how to navigate to a page passing just the route parameter.
function handler({api, event, imports, helpers}) {
helpers.navigate.to('test');
}
This example shows how to navigate to a page passing the route and fields parameters.
function handler({api, event, imports, helpers}) {
helpers.navigate.to('test', {'key': 'value'});
}
This example shows how to navigate to a page passing the route, fields, and params parameters.
function handler({api, event, helpers, imports}) {
helpers.navigate.to('test', {'key': 'value'}, {'first': 'FirstName', 'last': 'Last Name'});
}
helpers - helpers.screen.updateStatus(Object statusObj)
Enables pages to report their status updates, such as title, icon, dirty state, message, and error changes.
Status updates are reported to WorkspaceChrome or AppShell, whichever the outer layer is, and acting as the host.
| Name | Type | Description |
|---|---|---|
| statusObj | Object | Payload to send to the current page to report that the content has been
updated. Valid values:
|
| Type | Description |
|---|---|
| None |
screen.updateStatus({'dirtyModalId': 'customModalId', 'isDirty': true});
helpers - helpers.snHttp(String url, Object options)
Makes an HTTP request to the ServiceNow instance and returns a promise with the results.
{
options: {},
otherFields: {}
}
becomes
{
otherFields: {}
}| Name | Type | Description |
|---|---|---|
| url | String | HTTP endpoint relative to the instance URL. For example,
/api/now/table/incident or
/api/now/table/incident/a83820b58f723300e7e16c7827bdeed. |
| options | Object | Describes the contents of the HTTP
request. |
| options.batch | Boolean | Optional. Flag that indicates whether this HTTP request should be batched with
other HTTP requests made to the instance. Valid values:
Default: true |
| options.body | Object | Optional. Data to send as the request body. Only applicable for request methods
PUT, POST, and PATCH. Elements
in the object depend on the type of HTTP method. For details, refer to the code
examples below.Default: |
| options.headers | Object | Optional. Additional HTTP request headers. For example: |
| options.method | String | Optional. HTTP method. Valid values:
Default: GET |
| Type | Description |
|---|---|
| error | Object that describes any error returned by the REST API. Data type: Object |
| error.data | Response returned from the HTTP API. Data type: Defined by REST API |
| error.message | Message describing the error encountered when trying to process the HTTP
request. 注:
This parameter is not always returned. Data type: String |
| error.options | Describes the original HTTP request. Data type: Object |
| error.options.headers | Object containing a list of all of the request headers sent in the
request. Data type: Object |
| error.options.responseHeaders | Object containing a list of all of the response headers sent in the
request. Data type: Object |
| error.status | Returned HTTP error status code, such as 400, 405, or 500. Data type: Number |
| error.statusText | Returned HTTP status message, such as Bad Request.
Data type: String |
| response | Returned when HTTP request is successful. The response to the HTTP
request. Data type: Any |
The following example show how to call snHttp() which returns a promise.
function handler({api, event, helpers, imports}) {
helpers.snHttp('/api/now/table/u_movie', {method: 'GET'})
.then(({response}) => {
// do something with the table data
})
.catch(({error}) => {
const message = `Error: ${error.data.error.message}`;
console.error(message);
api.emit('NOW_UXF_PAGE#ADD_NOTIFICATIONS', {
id: 'alert5',
status: 'high',
icon: 'info-circle-outline',
content: message,
action: { type: 'dismiss' }
});
});
}
The following example show how to call snHttp() using async and await.
async function handler({helpers}) {
try {
const result = await helpers.snHttp('/api/now/table/u_movie', {method: 'GET'});
} catch ({error}) {
const message = `Error: ${error.data.error.message}`;
console.error(message);
api.emit('NOW_UXF_PAGE#ADD_NOTIFICATIONS', {
id: 'alert5',
status: 'high',
icon: 'info-circle-outline',
content: message,
action: { type: 'dismiss' }
});
}
}
The following example show how to set up a POST request.
function handler({api, helpers, event, imports}) {
helpers
.snHttp("/api/now/table/incident", {
method: "POST",
body: {
description: "Sample description",
close_notes: "Sample close notes",
order: "-1"
}
})
.then(({ response }) => {
// handle POST request response
})
.catch(({ error }) => {
// handle POST request errors
});
}
The following example show how to set up a PUT request.
function handler({api, helpers, event, imports}) {
helpers
.snHttp("/api/now/table/incident/a83820b58f723300e7e16c7827bdeed2", {
method: "PUT",
body: {
activity_due: "1970-04-02 18:26:17"
},
headers: {
"Content-Type": "application/json",
"Accept": "application/xml"
}
})
.then(({ response }) => {
// handle PUT request response
})
.catch(({ error }) => {
// handle PUT request errors
});
}
helpers - helpers.timing.clearInterval(Number timeoutId)
Cancels the execution of the function that was scheduled through a prior setInterval() call.
| Name | Type | Description |
|---|---|---|
| timeoutId | Number | Unique identifier of the scheduled function to clear. This value is returned by the corresponding setInterval() call. |
| Type | Description |
|---|---|
| None |
This example shows using clearInterval() to cancel a timing operation that was previously set using thesetInterval() method. This function could be invoked by a user clicking a Disable Auto-refresh button on a page.
function handler({api, helpers}) {
api.setState('intervalId', ({currentValue}) => {
if (currentValue > -1) {
helpers.timing.clearInterval(currentValue);
}
return -1;
});
}
helpers - helpers.timing.clearTimeout(Number timeoutId)
Cancels the execution of the function that was scheduled through a prior setTimeout() call.
| Name | Type | Description |
|---|---|---|
| timeoutId | Number | Unique identifier of the scheduled function to clear. This value is returned by the corresponding setTimeout() call. |
| Type | Description |
|---|---|
| None |
This code example shows how to terminate a timer with the specified timeoutId.
function handler({api, helpers}) {
api.setState('timeoutId', ({currentValue}) => {
if (currentValue > -1) {
helpers.timing.clearTimeout(currentValue);
}
return -1;
});
}
helpers - helpers.timing.setInterval(Function fn, Number delay)
Repeatedly executes the specified function, using the specified delay value as the interval between function calls.
Unlike the native JavaScript setInterval() method, this method does not support passing a code string to evaluate as the first argument. Any additional arguments are passed to the function itself.
| Name | Type | Description |
|---|---|---|
| fn | Function | Function to repeatedly execute. |
| delay | Number | Length of the time-interval between each function execution. Unit: Milliseconds |
| Type | Description |
|---|---|
| Number | Unique identifier of the function execution operation. Use this value in the helpers - helpers.timing.clearInterval(Number timeoutId) method if you need to cancel this operation. |
This code example shows how to refresh the timestamp on a page every second. This function could be invoked by a user clicking an Enable Auto-refresh button on a page.
function handler({api, helpers}) {
// Every one second, refresh the value of current timestamp client state parameter
const intervalId = helpers.timing.setInterval(() => {
api.setState('currentTimestamp', new Date().toString())
}, 1000);
// The interval ID is kept in state to use when calling the helpers.timing.clearInterval() method at a later point
api.setState('intervalId', intervalId);
}
helpers - helpers.timing.setTimeout(Function fn, Number delay)
Executes the specified function, after the specified delay.
Unlike the native JavaScript setTimeout() method, this method does not support passing a code string to evaluate as the first argument. Any additional arguments are passed to the function itself.
| Name | Type | Description |
|---|---|---|
| fn | Function | Function to execute. |
| delay | Number | Length of the time to wait before calling the specified function. Unit: Milliseconds |
| Type | Description |
|---|---|
| Number | Unique identifier of the function execution operation. Use this value in the helpers - helpers.timing.clearTimeout(Number timeoutId) method if you need to cancel this operation. |
This code example shows how to set a 20 minute timer. You could associate this function with a button Remind me in 20 minutes.
function handler({api, helpers}) {
const timeoutId = helpers.timing.setTimeout(() => {
api.emit('NOW_UXF_PAGE#ADD_NOTIFICATIONS', {
id: 'alert5',
status: 'high',
icon: 'info-circle-outline',
content: 'Try to look away at something that is 20 feet away from you for a total of 20 minutes.',
action: { type: 'dismiss' }
});
}, 20 * 60 * 1000);
// The timeout ID is kept in state to use when calling the helpers.timing.clearTimeout() method at a later point
api.setState('timeoutId', timeoutId);
}
helpers - helpers.translate(String message, String tokens)
Asynchronously retrieves and translates the specified message based on the current user's session language.
You can use this method with the api - setState(String stateParam, Any value) to bind the translated value to other fields on the page.
async and
await. The code examples below show both implementations.| Name | Type | Description |
|---|---|---|
| message | String | Message to translate. |
| tokens | String | Optional. Comma-separated list of parameters to use for replacing string
variables. For example: |
| Type | Description |
|---|---|
| String | Translated text string. |
The following example shows how to pass in table field references to embed in the corresponding variables in a string, using a promise.
function handler ({api, helpers}) {
helpers.translate('Welcome {0} {1}!', user.firstName, user.lastName)
.then((translatedText) => {
api.setState('greeting', translatedText);
});
}
The following example shows how to use async and await in
your function instead of a promise.
async function handler ({api, helpers}) {
const translatedText = await helpers.translate('Welcome to {0}', 'ServiceNow');
api.setState('greeting', translatedText);
}