### Embed Widgets and Get Server Data with spUtil
Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index
Methods for embedding other Service Portal widgets or fetching their models. `get` can fetch a widget model, optionally with data, and returns a promise. This is useful for dynamically loading or interacting with other widgets.
```javascript
spUtil.get("widget-cool-clock").then(function(response) {
c.coolClock = response;
});
```
```javascript
spUtil.get('pps-list-modal', {
title: c.data.editAllocations,
table: 'resource_allocation',
queryString: 'GROUPBYuser^resource_plan=' + c.data.sysId,
view: 'resource_portal_allocations'
}).then(function(response) {
var formModal = response;
c.allocationListModal = response;
});
```
--------------------------------
### spUtil - User Preferences and Data Management
Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index
Methods for getting and setting user preferences, updating server data, and watching for record changes.
```APIDOC
## spUtil.getPreference(String preference, Function callback)
### Description
Executes the callback with User Preference response by passing the preference name.
### Method
client script function
### Endpoint
N/A
### Parameters
* **preference** (String) - The name of the user preference to retrieve.
* **callback** (Function) - The function to execute with the preference value.
### Response
N/A
## spUtil.setPreference(String pref, String value)
### Description
Sets a user preference.
### Method
client script function
### Endpoint
N/A
### Parameters
* **pref** (String) - The name of the preference to set.
* **value** (String) - The value to set for the preference.
### Response
N/A
## spUtil.update(Object $scope)
### Description
Updates the data object on the server within a given scope.
### Method
client script function
### Endpoint
N/A
### Parameters
* **$scope** (Object) - The scope object for the widget.
### Response
N/A
## spUtil.recordWatch(Object $scope, String table, String filter, Function callback)
### Description
Watches for updates to a table or filter and returns the value from the callback function.
### Method
client script function
### Endpoint
N/A
### Parameters
* **$scope** (Object) - The scope object for the widget.
* **table** (String) - The name of the table to watch.
* **filter** (String) - The filter to apply to the table.
* **callback** (Function) - The function to execute when a change is detected.
### Response
N/A
```
--------------------------------
### Get All Context Data with spContextManager (JavaScript)
Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index
The spContextManager.getContext() method retrieves all initialized keys and their associated data objects currently defined by widgets on the page. Use this to understand the page's context state. Be aware that its usage may impact performance; prefer getContextForKey() for specific data retrieval.
```javascript
function($scope, spContextManager) {
spContextManager.getContext();
}
```
--------------------------------
### Get Specific Context Data with spContextManager (JavaScript)
Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index
The spContextManager.getContextForKey() method retrieves widget data associated with a specific key. It can return data directly as an object or as a promise if the 'returnPromise' parameter is set to true, which resolves when the key is initialized by another widget. This is useful for accessing specific data points, like 'approval_count' for Agent Chat.
```javascript
function($scope, spContextManager) {
spContextManager.getContextForKey('agent-chat', true).then(function(context) {
context = context || {};
context.approval_count = 5;
spContextManager.updateContextForKey('agent-chat', context);
});
}
```
--------------------------------
### Scroll to Element with Animation - JavaScript
Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index
The scrollTo function animates scrolling to a specific element identified by a CSS selector over a defined duration. This is useful for guiding user attention within the page.
```javascript
spUtil.scrollTo(selector, time);
```
--------------------------------
### spUtil - Server and Environment Information
Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index
Methods to retrieve headers, host domain, URL information, and check device type.
```APIDOC
## spUtil.getHeaders()
### Description
Retrieves all headers to use for API calls.
### Method
client script function
### Endpoint
N/A
### Parameters
N/A
### Response
Returns an object containing all headers.
## spUtil.getHost()
### Description
Returns the complete host domain.
### Method
client script function
### Endpoint
N/A
### Parameters
N/A
### Response
* **String**: The complete host domain, for example `hi.servicenow.com`.
## spUtil.getURL()
### Description
Returns the current service portal URL information.
### Method
client script function
### Endpoint
N/A
### Parameters
N/A
### Response
Returns an object containing URL information.
## spUtil.isMobile()
### Description
Checks if the current client is a mobile device.
### Method
client script function
### Endpoint
N/A
### Parameters
N/A
### Response
* **Boolean**: `true` if the client is a mobile device, `false` otherwise.
```
--------------------------------
### Service Portal Modals - Prompt
Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index
Shows how to use the `spModal.prompt` function to display a modal dialog that asks the user for text input, returning the input value via a promise.
```APIDOC
## POST /spModal/prompt
### Description
Displays a modal dialog prompting the user to enter text. The entered value is returned via a promise, allowing for client-side scripting to capture and use the user's input.
### Method
POST
### Endpoint
/spModal/prompt
### Parameters
#### Arguments
- **message** (String) - Required - The prompt message displayed to the user.
- **defaultValue** (String) - Optional - The default value pre-filled in the input field.
### Example
```javascript
// Client script function to trigger a prompt
function(spModal) {
var c = this;
c.onPrompt = function() {
spModal.prompt("Your name please", c.name).then(function(name) {
c.name = name;
})
}
}
```
### Response
#### Success Response (200)
The promise resolves with the string value entered by the user in the prompt, or `null` if the prompt was cancelled or dismissed without input.
```
--------------------------------
### spUtil - UI and Display Helpers
Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index
Methods for parsing attributes, scrolling, updating breadcrumbs, and search pages.
```APIDOC
## spUtil.parseAttributes(String attributes)
### Description
Parses the comma-separated attributes within a specified string.
### Method
client script function
### Endpoint
N/A
### Parameters
* **attributes** (String) - The string containing comma-separated attributes.
### Request Example
```javascript
function getRefQualElements() {
var refQualElements = [];
if (field && field.attributes && field.attributes.indexOf('ref_qual_elements') > -1) {
var attributes = spUtil.parseAttributes(field.attributes);
refQualElements = attributes['ref_qual_elements'].split(';');
}
return refQualElements;
}
```
### Response
Returns an object where keys are attribute names and values are attribute values.
## spUtil.scrollTo(String selector, Number time)
### Description
Scrolls to the element with the specified selector, over a specified period of time.
### Method
client script function
### Endpoint
N/A
### Parameters
* **selector** (String) - The CSS selector for the element to scroll to.
* **time** (Number) - The duration of the scroll animation in milliseconds.
### Response
N/A
## spUtil.setBreadCrumb($scope, Array breadcrumbs)
### Description
Updates the header breadcrumbs.
### Method
client script function
### Endpoint
N/A
### Parameters
* **$scope** (Object) - The scope object for the widget.
* **breadcrumbs** (Array) - An array of breadcrumb objects, each with `label` and `url` properties.
### Response
N/A
## spUtil.setSearchPage(String searchPage)
### Description
Updates the search page.
### Method
client script function
### Endpoint
N/A
### Parameters
* **searchPage** (String) - The name or ID of the search page to set.
### Response
N/A
## spUtil.refresh($scope)
### Description
Calls the server and replaces the current options and data with the server response.
### Method
client script function
### Endpoint
N/A
### Parameters
* **$scope** (Object) - The scope object for the widget.
### Response
N/A
```
--------------------------------
### Open Modal Dialog with Input using spModal
Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index
Demonstrates using `spModal.open()` to create a modal dialog that prompts the user for text input. The `input: true` option enables the text field, and the `value` option pre-populates it. The promise resolves with the user's input. Requires `spModal` injection.
```html
//HTML template
You answered {{c.name}}
```
```javascript
//Client code
function(spModal) {
var c = this;
c.onOpen = function() {
//ask the user for a string
spModal.open({
title: 'Give me a name',
message: 'What would you like to name it?',
input: true,
value: c.name
}).then(function(name) {
c.name = name;
})
}
}
```
--------------------------------
### Retrieve Service Portal Information with spUtil
Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index
Functions to retrieve essential information about the current Service Portal environment. `getHeaders` provides API headers, `getHost` returns the domain, `getURL` provides the current portal URL, and `isMobile` checks for mobile device access.
```javascript
var apiHeaders = spUtil.getHeaders();
```
```javascript
var hostDomain = spUtil.getHost();
// Example: 'hi.servicenow.com'
```
```javascript
var portalUrlInfo = spUtil.getURL();
```
```javascript
var isMobileDevice = spUtil.isMobile();
```
--------------------------------
### Parse Attributes and Watch Records with spUtil
Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index
Utility for parsing string attributes and setting up real-time data watches. `parseAttributes` converts a comma-separated attribute string into an object, and `recordWatch` monitors table changes and executes a callback.
```javascript
function getRefQualElements() {
var refQualElements = [];
if (field && field.attributes && field.attributes.indexOf('ref_qual_elements') > -1) {
var attributes = spUtil.parseAttributes(field.attributes);
refQualElements = attributes['ref_qual_elements'].split(';');
}
return refQualElements;
}
```
```javascript
spUtil.recordWatch($scope, 'incident', 'active=true', function(serverData) {
// Callback function to process record updates
console.log('Incident updated:', serverData);
});
```
--------------------------------
### Initialize Context with spContextManager (JavaScript)
Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index
The spContextManager.addContext() method initializes a key and associates widget data with it, making it available to other Service Portal applications like Agent Chat. This method should be used only when the key is not already in use on the page. It takes a string key and a JSON object as parameters.
```javascript
function($scope, spContextManager) {
spContextManager.addContext('agent-chat', {
'approval_count': 5
});
};
```
--------------------------------
### Manage User Preferences with spUtil
Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index
Functions for interacting with user preferences. `getPreference` retrieves a user preference asynchronously via a callback, while `setPreference` allows setting a user preference value.
```javascript
spUtil.getPreference('user_language', function(preferenceValue) {
console.log('User language preference:', preferenceValue);
});
```
```javascript
spUtil.setPreference('theme', 'dark');
```
--------------------------------
### Display Confirmation Dialog using spModal
Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index
Uses `spModal.confirm()` to display a confirmation message, allowing the user to confirm or deny an action. The promise resolves to a boolean indicating the user's choice. Requires `spModal` injection. Also demonstrates how to use `spModal.open()` with custom options for more complex dialogs including HTML content.
```html
{{c.confirmed}}
```
```javascript
function(spModal) {
var c = this;
c.onConfirm = function() {
c.confirmed = "asking";
spModal.confirm("Can you confirm or deny this?").then(function(confirmed) {
c.confirmed = confirmed; // true or false
})
}
}
```
```html
//HTML template
{{c.confirmed}}
```
```javascript
// Client script
function(spModal) {
var c = this;
// more control, passing options
c.onConfirmEx = function() {
c.confirmed = "asking";
var warn = '';
spModal.open({
title: 'Delete this Thing?',
message: warn + ' Are you sure you want to do that?'
}).then(function(confirmed) {
c.confirmed = confirmed;
})
}
}
```
--------------------------------
### spUtil - Data Manipulation and Utility
Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index
Methods for creating unique identifiers, formatting strings, embedding widgets, and retrieving server data.
```APIDOC
## spUtil.createUid()
### Description
Creates a unique identifier.
### Method
client script function
### Endpoint
N/A
### Parameters
N/A
### Response
Returns a unique string identifier.
## spUtil.format(String template, Object data)
### Description
Formats a string that contains variables. Use this method as an alternative to string concatenation.
### Method
client script function
### Endpoint
N/A
### Parameters
* **template** (String) - The template string containing variables in the format {variable}.
* **data** (Object) - An object containing key-value pairs for the variables.
### Request Example
```javascript
spUtil.format('An error ocurred: {error} when loading {widget}', {error: '404', widget: 'sp-widget'});
```
### Response
Returns the formatted string.
## spUtil.get(String widgetId, Object data)
### Description
Embeds a widget model in a widget client script. The callback function returns the full widget model.
### Method
client script function
### Endpoint
N/A
### Parameters
* **widgetId** (String) - The ID of the widget to embed.
* **data** (Object) - Optional. Data to pass to the widget.
### Request Example
Without data passed:
```javascript
spUtil.get("widget-cool-clock").then(function(response) {
c.coolClock = response;
});
```
With data passed:
```javascript
spUtil.get('pps-list-modal', {
title: c.data.editAllocations,
table: 'resource_allocation',
queryString: 'GROUPBYuser^resource_plan=' + c.data.sysId,
view: 'resource_portal_allocations'
}).then(function(response) {
var formModal = response;
c.allocationListModal = response;
});
```
### Response
Returns a promise that resolves with the widget model.
```
--------------------------------
### Service Portal Modals - Custom Buttons
Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index
Demonstrates how to use the `spModal` service to open a modal dialog with custom buttons and handle user responses. This is useful for confirmations or multi-option dialogs.
```APIDOC
## POST /spModal/open (Custom Buttons)
### Description
Opens a modal dialog with custom buttons, allowing for user interaction and response handling. This is commonly used for confirmations or scenarios requiring user input through predefined choices.
### Method
POST
### Endpoint
/spModal/open
### Parameters
#### Request Body
- **title** (String) - Required - The title of the modal dialog.
- **message** (String) - Required - The main content message of the modal, can include HTML.
- **buttons** (Array