### Example: Embedding Multiple Widgets with Custom Options Source: https://serviceportal.io/docs/documentation/widget_embedded.md A comprehensive example showing how to embed multiple instances of the same widget with different configurations using server-side data. ```APIDOC ## Example: How to embed a widget multiple times with custom options Each instance of the clock is provided a different timezone and title. Edit the "Embedded clock" widget and replace with the following code blocks: ###### HTML Template ```html
Time across the US
``` ###### CSS ```css .panel { margin-top: 10px; } ``` ###### Client Script ```javascript function() { // nothing to do here... } ``` ###### Server Script ```javascript (function() { var options = [ {zone: "America/Los_Angeles", title: "San Diego"}, {zone: "America/Denver", title: "Denver"}, {zone: "America/Chicago", title: "Chicago"}, {zone: "America/New_York", title: "New York"} ]; data.clocks = []; for (var i in options) { data.clocks.push($sp.getWidget("widget-cool-clock", options[i])); } })(); ``` ``` -------------------------------- ### $sp.getCatalogItem Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Retrieves a model and view model for a catalog item or guide. ```APIDOC ## $sp.getCatalogItem ### Description Returns a model and view model for a sc_cat_item or sc_cat_item_guide. ### Method $sp.getCatalogItem(String) ### Parameters - **String** (sys_id or name) - The sys_id or name of the catalog item or guide. ``` -------------------------------- ### g_service_catalog API: Is Order Guide Source: https://serviceportal.io/docs/documentation/client_scripting.md Checks if the current item being viewed is an order guide. ```javascript g_service_catalog.isOrderGuide() ``` -------------------------------- ### Get Catalog Item Data with $sp.getCatalogItem Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Use $sp.getCatalogItem to fetch all data needed to render and order a catalog item. For simple display of item name or picture, consider GlideRecord. This example shows its usage with $sp.getParameter. ```javascript (function() { var sys_id = $sp.getParameter("sys_id") data.catItem = $sp.getCatalogItem(sys_id); })(); ``` -------------------------------- ### get Source: https://serviceportal.io/docs/documentation/widget_client_script_apis.md Fetches a widget model by its ID or sys_id. Returns a Promise. ```APIDOC ## get(String widgetId) ### Description Gets a widget model by id or sys_id. Returns a Promise. ### Method Signature `spUtil.get(widgetId)` ### Parameters * **widgetId** (String) - The ID or sys_id of the widget to retrieve. ### Returns A Promise that resolves with the widget model. ### Request Example ```javascript spUtil.get("widget-cool-clock").then(function(response) { c.coolClock = response; }); ``` ``` -------------------------------- ### $sp.getWidget() Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Gets a widget by its ID or sys_id, executes its server script with provided options, and returns the widget model. ```APIDOC ## $sp.getWidget(widget_id, options) ### Description Gets a widget by id or sys_id, executes that widget's server script using the provided options, then returns the widget model. ### Method Signature `$sp.getWidget( widget_id, options ): Object` ### Parameters #### Parameters * **widget_id** (_String_) - Can be a widget_id or widget sys_id. * **options** (_Object_) - An object to pass to the widget's server script. Refer to this object as **options** in your server script. ### Returns * (_Object_) A widget model to be used with \. ``` -------------------------------- ### Check if Catalog Item is part of Order Guide Source: https://serviceportal.io/docs/documentation/client_scripting.md The g_service_catalog API is available in Service Portal catalog item scripts. Use g_service_catalog.isOrderGuide() to determine if the item is part of an order guide. ```javascript function onLoad() { if (window) // if CMS don't run this return; // g_service_catalog api for Service Portal and Mobile var isOrderGuide = g_service_catalog.isOrderGuide(); g_form.setValue("is_order_guide", isOrderGuide ? "Yes!" : "Nope :("); } ``` -------------------------------- ### Get Widget Model - Server Script Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Fetches a widget by its ID or sys_id, executes its server script with provided options, and returns the widget model. Use this to embed dynamic content from other widgets. ```javascript data.myWidget = $sp.getWidget('widget_id', {p1: param1, p2: param2}); ``` -------------------------------- ### Server-Side Get Widget Model ($sp.getWidget) Source: https://serviceportal.io/docs/documentation/widget_embedded.md Retrieves a widget model using its ID and options. This is the server-side equivalent of `spUtil.get()`. Options passed here are available as `options` in the embedded widget's server script. ```JavaScript data.catalogItemWidget = $sp.getWidget("widget-sc-cat-item", {sys_id: "your_catalog_item_sys_id"}); ``` -------------------------------- ### GlideAjax: Get Parameters Source: https://serviceportal.io/docs/documentation/client_scripting.md Returns all parameters currently set for the GlideAjax request. ```javascript new GlideAjax(scriptIncludeName).getParams() ``` -------------------------------- ### GlideAjax: Get URL Source: https://serviceportal.io/docs/documentation/client_scripting.md Returns the URL that will be used for the GlideAjax request. ```javascript new GlideAjax(scriptIncludeName).getURL() ``` -------------------------------- ### Get Widget Instance and Portal Values Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Use $sp.getValue() to retrieve 'title' from the widget instance and 'sc_catalog' from the portal record. Assign these values to the data object for use in the HTML template. ```javascript (function() { data.title = $sp.getValue("title"); data.catalog = $sp.getValue("sc_catalog"); })(); ``` -------------------------------- ### GlideRecord: Get Table Name Source: https://serviceportal.io/docs/documentation/client_scripting.md Returns the name of the table the GlideRecord object is currently querying. ```javascript new GlideRecord(tableName).getTableName() ``` -------------------------------- ### g_form API: Get Label Source: https://serviceportal.io/docs/documentation/client_scripting.md Retrieves the label of a specified form field. ```javascript g_form.getLabel(fieldName) ``` -------------------------------- ### GlideRecord: Get Record by ID Source: https://serviceportal.io/docs/documentation/client_scripting.md Retrieves a specific record from the table based on its sys_id. ```javascript new GlideRecord(tableName).get(id) ``` -------------------------------- ### Get Widget Model with spUtil Source: https://serviceportal.io/docs/documentation/widget_client_script_apis.md Fetches a widget model by its ID or sys_id. Returns a Promise that resolves with the widget data. Ensure the widget ID is correct. ```javascript spUtil.get("widget-cool-clock").then(function(response) { c.coolClock = response; }); ``` -------------------------------- ### GlideRecord: Get Limit Source: https://serviceportal.io/docs/documentation/client_scripting.md Retrieves the maximum number of records that will be returned by the query. ```javascript new GlideRecord(tableName).getLimit() ``` -------------------------------- ### g_form API: Get Section Names Source: https://serviceportal.io/docs/documentation/client_scripting.md Retrieves an array of all section names available on the form. ```javascript g_form.getSectionNames() ``` -------------------------------- ### g_form API: Get Value Source: https://serviceportal.io/docs/documentation/client_scripting.md Retrieves the current value of a specified field on the form. ```javascript g_form.getValue(fieldName) ``` -------------------------------- ### g_form API: Get Table Name Source: https://serviceportal.io/docs/documentation/client_scripting.md Returns the name of the table associated with the current form. ```javascript g_form.getTableName() ``` -------------------------------- ### g_form API: Get Field Names Source: https://serviceportal.io/docs/documentation/client_scripting.md Retrieves an array of all field names present on the current form. ```javascript g_form.getFieldNames() ``` -------------------------------- ### spUtil.get() - Get Widget Model Client-Side Source: https://serviceportal.io/docs/documentation/widget_embedded.md Retrieves a widget model using the `spUtil.get()` method in a client script. This is useful for dynamically loading and embedding widgets. ```APIDOC ### Client Side ##### spUtil.get() - Get a widget model via client script ```javascript spUtil.get("widget-sc-cat-item", {sys_id: "your_catalog_item_sys_id"}).then(function(response) { c.catalogItemWidget = response; }); ``` **Parameters** * (string) widget_id Can be a widget_id or widget sys_id. * (object) data An object to post to the widget's server script. Refer to this object as **input** in your server script. **Callback** The callback function is called when the widget model is ready. The response object contains the full widget model. ``` -------------------------------- ### $sp.getWidget() - Get Widget Model Server-Side Source: https://serviceportal.io/docs/documentation/widget_embedded.md Obtains a widget model using the `$sp.getWidget()` method in a server script. This method allows passing options to the embedded widget's server script. ```APIDOC ### Server Side ##### $sp.getWidget() - Get a widget model via server script ```javascript data.catalogItemWidget = $sp.getWidget("widget-sc-cat-item", {sys_id: "your_catalog_item_sys_id"}); ``` **Parameters** * (string) widget_id Can be a widget_id or widget sys_id. * (object) options An object to pass to the widget's server script. Refer to this object as **options** in your server script. **Note:** As of all versions of Helsinki, any options passed into this function will only be available in the embedded widget's server script on the **first execution** of that script. Any subsequent calls into the server script from the embedded widget will not contain the object properties passed in. This is something we are investigating for a future version of Helisinki or Istanbul. ``` -------------------------------- ### Client-Side Get Widget Model (spUtil.get) Source: https://serviceportal.io/docs/documentation/widget_embedded.md Retrieves a widget model using its ID and optional data. Useful for dynamically loading widgets or fetching widget data client-side. The `data` object is available as `input` in the widget's server script. ```JavaScript spUtil.get("widget-sc-cat-item", {sys_id: "your_catalog_item_sys_id"}).then(function(response) { c.catalogItemWidget = response; }); ``` -------------------------------- ### Get Message Source: https://serviceportal.io/docs/documentation/client_scripting.md Retrieves a translated message string based on a message key. Supports an optional callback for asynchronous retrieval. ```javascript getMessage(messageKey, callback) ``` -------------------------------- ### Get Current Portal Record - Server Script Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Retrieves the current portal's GlideRecord to access its properties like logo and homepage. Ensure the script runs in a context where the portal is defined. ```javascript (function() { var portalGr = $sp.getPortalRecord(); data.logo = portalGr.getDisplayValue("logo"); data.homepage = portalGr.getDisplayValue("homepage.id"); })(); ``` -------------------------------- ### g_form API: Get Action Name Source: https://serviceportal.io/docs/documentation/client_scripting.md Retrieves the name of the UI action that triggered the current client script execution. ```javascript g_form.getActionName() ``` -------------------------------- ### g_form API: Get Sys ID Source: https://serviceportal.io/docs/documentation/client_scripting.md Retrieves the system ID (sys_id) of the current record. ```javascript g_form.getSysId() ``` -------------------------------- ### GlideRecord: Get Encoded Query Source: https://serviceportal.io/docs/documentation/client_scripting.md Retrieves the current encoded query string applied to the GlideRecord object. ```javascript new GlideRecord(tableName).getEncodedQuery() ``` -------------------------------- ### g_form API: Get Display Value Source: https://serviceportal.io/docs/documentation/client_scripting.md Retrieves the user-friendly display value of a field, such as a reference field's label. ```javascript g_form.getDisplayValue(fieldName) ``` -------------------------------- ### g_list API: Get Default Operator Source: https://serviceportal.io/docs/documentation/client_scripting.md Retrieves the default operator for the list collector's query. ```javascript g_list.getDefaultOperator() ``` -------------------------------- ### GlideAjax: Get Parameter Source: https://serviceportal.io/docs/documentation/client_scripting.md Retrieves a parameter value from the GlideAjax request. Useful within the script include. ```javascript new GlideAjax(scriptIncludeName).getParam(name) ``` -------------------------------- ### g_form API: Get Reference Source: https://serviceportal.io/docs/documentation/client_scripting.md Asynchronously retrieves the value of a reference field. Requires a callback function to handle the result. ```javascript g_form.getReference(fieldName, callback) ``` -------------------------------- ### g_form API: Get Encoded Record Source: https://serviceportal.io/docs/documentation/client_scripting.md Returns the encoded query string of the current record being viewed or edited. ```javascript g_form.getEncodedRecord() ``` -------------------------------- ### g_service_catalog API Source: https://serviceportal.io/docs/documentation/client_scripting.md The g_service_catalog API is available in Service Portal service catalog item scripts. It helps determine if a catalog item script is running as part of an order guide or independently. ```APIDOC ## g_service_catalog g_service_catalog is only available in Service Portal service catalog item scripts. Use this API to know if your catalog item script is being run as part of an order guide or on its own. ```javascript function onLoad() { if (window) // if CMS don't run this return; // g_service_catalog api for Service Portal and Mobile var isOrderGuide = g_service_catalog.isOrderGuide(); g_form.setValue("is_order_guide", isOrderGuide ? "Yes!" : "Nope :("); } ``` ``` -------------------------------- ### g_form API: Get Integer Value Source: https://serviceportal.io/docs/documentation/client_scripting.md Retrieves the integer value of a field. Suitable for whole number fields. ```javascript g_form.getIntValue(fieldName) ``` -------------------------------- ### g_form API: Get Related List Names Source: https://serviceportal.io/docs/documentation/client_scripting.md Returns an array containing the names of all related lists on the current form. ```javascript g_form.getRelatedListNames() ``` -------------------------------- ### GlideAjax: Get XML (Callback) Source: https://serviceportal.io/docs/documentation/client_scripting.md Sends an asynchronous GlideAjax request and processes the response using an XML callback function. ```javascript new GlideAjax(scriptIncludeName).getXML(callback) ``` -------------------------------- ### GlideAjax: Get JSON (Callback) Source: https://serviceportal.io/docs/documentation/client_scripting.md Sends an asynchronous GlideAjax request and processes the response as JSON using a callback function. ```javascript new GlideAjax(scriptIncludeName).getJSON(callback) ``` -------------------------------- ### Get Display Value with $sp.getDisplayValue Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Retrieve the display value of a field from the widget's sp_instance or the current sp_portal record. This is useful for fetching titles or catalog identifiers. ```javascript (function() { data.title = $sp.getDisplayValue("title"); data.catalog = $sp.getDisplayValue("sc_catalog"); })(); ``` -------------------------------- ### Providing Widget Options Server-Side Source: https://serviceportal.io/docs/documentation/widget_embedded.md Illustrates how to provide options to an embedded widget from the server script, referencing a data object in the HTML template. ```APIDOC ### Providing options server-side ###### HTML template ```html ``` ###### Server Script ```javascript (function() { data.clockOptions = {"zone": "America/Los_Angeles","title": "San Diego, CA"}; })(); ``` ``` -------------------------------- ### Provide Widget Options Server-Side Source: https://serviceportal.io/docs/documentation/widget_embedded.md Define widget options in the server script and reference them in the HTML template using the `options` attribute. This allows for dynamic option generation. ```HTML ``` ```JavaScript (function() { data.clockOptions = {"zone": "America/Los_Angeles","title": "San Diego, CA"}; })(); ``` -------------------------------- ### GlideAjax: Get XML Answer (Callback) Source: https://serviceportal.io/docs/documentation/client_scripting.md Sends an asynchronous GlideAjax request and retrieves the answer from the response using an XML callback function. ```javascript new GlideAjax(scriptIncludeName).getXMLAnswer(callback) ``` -------------------------------- ### $sp.getUserInitials Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Retrieves the current user's initials. ```APIDOC ## $sp.getUserInitials ### Description Returns the user's initials as a string. ### Method $sp.getUserInitials() ``` -------------------------------- ### GlideRecord: Get Value Source: https://serviceportal.io/docs/documentation/client_scripting.md Retrieves the value of a specified field for the current record. ```javascript new GlideRecord(tableName).getValue(fieldName) ``` -------------------------------- ### $sp.getCatalogItem() Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Retrieves all necessary data to render and order a catalog item. For simply displaying item information, consider using GlideRecord. ```APIDOC ## $sp.getCatalogItem() ### Description A quick way to get all of the data necessary to render and order a catalog item using \\. If you just need to get a catalog item to show its picture or name, consider using GlideRecord to query the sp_cat_item table. The following example demonstrates how to use getCatalogItem and \\ together. ### Method $sp.getCatalogItem( sys_id ) ### Parameters #### Path Parameters * **sys_id** (String) - Required - The sys_id of the catalog item(sc_cat_item) or order guide(sc_cat_item_guide). ### Returns #### Success Response * **Object** - An object containing the catalog item variable model, view, sections, pricing and client scripts. ### Request Example ```javascript (function() { var sys_id = $sp.getParameter("sys_id") data.catItem = $sp.getCatalogItem(sys_id); })(); ``` ``` -------------------------------- ### $sp.getInstanceRecord() Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Retrieves the widget instance GlideRecord for the current widget. ```APIDOC ## $sp.getInstanceRecord() ### Description Returns the widget instances GlideRecord. ### Method Unknown ### Parameters None ### Response Unknown ``` -------------------------------- ### $sp.log() Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Sends a message to the Service Portal log console. ```APIDOC ## $sp.log(message) ### Description Sends the specified message to the log console. ### Method Unknown ### Parameters * **message** (string) - Required - The message to log. ### Response Unknown ``` -------------------------------- ### Widget Client Controller Source: https://serviceportal.io/docs/documentation/widget_client_script.md This is the main controller for the widget. Use it to handle client-side logic and interact with the server. ```javascript function() { var c = this; c.update = function() { c.data.price = false; c.server.get({symbol: c.data.symbol}).then(function(r) { c.data.price = r.data.price; }); } } ``` -------------------------------- ### $sp.getFields Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Retrieves a comma-separated list of valid field names from a GlideRecord. ```APIDOC ## $sp.getFields ### Description Checks the specified field names, and returns a comma separated list of valid names. ### Method $sp.getFields(GlideRecord, String) ### Parameters - **GlideRecord** - The GlideRecord object. - **String** (field names) - A comma-separated string of field names to check. ``` -------------------------------- ### Setting Default Options in Server Script Source: https://serviceportal.io/docs/documentation/widget_options.md Provide default values for widget options in the server script to handle cases where an option has not yet been set on an instance. This prevents undefined values. ```javascript (function() { options.text_color = options.text_color || "blue"; options.maximum_entry_count = options.maximum_entry_count || 5; }) ``` -------------------------------- ### GlideRecord: Set Display Fields Source: https://serviceportal.io/docs/documentation/client_scripting.md Specifies which fields should be returned in the query results, optimizing performance. ```javascript new GlideRecord(tableName).setDisplayFields(fieldNames) ``` -------------------------------- ### Embedding Widgets Client-Side Source: https://serviceportal.io/docs/documentation/widget_embedded.md Explains how to embed a widget dynamically using the `sp-widget` directive in the HTML template and fetching it via `spUtil.get()` in the client script. ```APIDOC ### Embedded Widgets client-side ###### HTML Template ```html ``` ###### Client Script ```javascript function(spUtil) { var c = this; spUtil.get("widget-cool-clock").then(function(response) { c.myClockWidget = response; }); } ``` ``` -------------------------------- ### $sp.getPortalRecord() Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Retrieves the current portal context. It returns the sp_portal GlideRecord if one exists. ```APIDOC ## $sp.getPortalRecord() ### Description Useful for getting the current portal context. It returns the sp_portal GlideRecord if there is one. ### Method Signature `$sp.getPortalRecord()` ### Parameters None ### Returns * (_GlideRecord_) The sp_portal record of the current portal context or null. ``` -------------------------------- ### Embedding Widgets in HTML Template Source: https://serviceportal.io/docs/documentation/widget_embedded.md Demonstrates the basic syntax for embedding a widget using the `` directive in an HTML template. ```APIDOC ## Widget Directive Syntax You can embed any widget inside of your widget’s HTML template using the custom `` element. The basic usage looks like this: ###### HTML Template ```html
``` _The `id` parameter is simply the id of the widget you're trying to embed._ ``` -------------------------------- ### $sp.getWidget Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Retrieves a widget model for embedding a widget within another widget. ```APIDOC ## $sp.getWidget ### Description Returns a widget model for embedding a widget inside another widget. ### Method $sp.getWidget(String, Object) ### Parameters - **String** (widget name or sys_id) - The name or sys_id of the widget to embed. - **Object** (options) - An object containing options for the embedded widget. ``` -------------------------------- ### g_form API: Get Boolean Value Source: https://serviceportal.io/docs/documentation/client_scripting.md Retrieves the boolean value of a field. Returns true or false. ```javascript g_form.getBooleanValue(fieldName) ``` -------------------------------- ### Populate Data from GlideRecord with $sp.getRecordElements Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Copies display values for specified fields from a GlideRecord into the data object. Ensure the data object and GlideRecord are properly instantiated. ```javascript (function($sp) { var gr = new GlideRecord("tablename"); var fieldnames = "sys_id,field_name"; $sp.getRecordElements(data, gr, fieldnames); })($sp); ``` -------------------------------- ### Providing Widget Options in HTML Template Source: https://serviceportal.io/docs/documentation/widget_embedded.md Shows how to pass options to an embedded widget directly within the HTML template using the `options` attribute. ```APIDOC ## Widget Options Widgets might have options that you can setup. You can define their values in JSON format: ### Providing options in the HTML template ###### HTML Template ```html ``` ``` -------------------------------- ### Accessing Options in Server Script Source: https://serviceportal.io/docs/documentation/widget_options.md Access widget instance options within the server-side script. Use $sp.log to output values to the browser console. ```javascript (function() { $sp.log(options.text_color) //Logs the value of the text_color option to the browser console. })(); ``` -------------------------------- ### Accessing Options in Client Script Source: https://serviceportal.io/docs/documentation/widget_options.md Access widget instance options within the client-side JavaScript. Ensure the option name matches the schema definition. ```javascript function() { /* widget controller */ var c = this; console.log(c.options.text_color) //Outputs the text_color option for this instance } ``` -------------------------------- ### $sp.getMenuHREF Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Generates the URL portion for a menu item based on its type. ```APIDOC ## $sp.getMenuHREF ### Description Returns the (?id=) portion of the URL based on the sp_menu type. ### Method $sp.getMenuHREF(GlideRecord) ### Parameters - **GlideRecord** (sp_menu) - The GlideRecord of the menu item. ``` -------------------------------- ### $sp.logSearch() Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Adds a record to the Service Portal Statistics logs. ```APIDOC ## $sp.logSearch() ### Description Adds a record to the Service Portal Statistics logs. ### Method Unknown ### Parameters None ### Response Unknown ``` -------------------------------- ### Implement Language Switch Widget Source: https://serviceportal.io/docs/documentation/widget_internationalization.md This widget allows users to change the portal's language. It uses a record picker for language selection and updates user preferences on the server. ```HTML
${Change Language}:
``` ```JavaScript function($window) { var c = this; c.language = {value: 'en', displayValue: 'English'}; c.changed = function(a) { c.server.get(c.language).then(function() { $window.location.reload(); }) } } ``` ```JavaScript (function() { if (input) { var user = gs.getUser(); user.setPreference("user.language", input.value); user.savePreferences(); } })(); ``` -------------------------------- ### Format String with spUtil Source: https://serviceportal.io/docs/documentation/widget_client_script_apis.md Provides an alternative to string concatenation for building strings with variables. Use placeholders like {variableName} and provide an object with corresponding keys and values. ```javascript spUtil.format('An error ocurred: {error} when loading {widget}', {error: '404', widget: 'sp-widget'}) ``` -------------------------------- ### $sp.getPortalRecord Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Retrieves the GlideRecord for the current portal. ```APIDOC ## $sp.getPortalRecord ### Description Returns the portal's GlideRecord. ### Method $sp.getPortalRecord() ``` -------------------------------- ### $sp.getRecordElements() Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Copies display values for specified field names from a GlideRecord into the data parameter. ```APIDOC ## $sp.getRecordElements() ### Description Copies display values for the specified field names from a GlideRecord into the data parameter. ### Method $sp.getRecordElements( data, GlideRecord, String ) ### Parameters #### Path Parameters * **data** (Object) - Required - Must pass data object instantiated by the server. * **GlideRecord** (GlideRecord) - Required - Any GlideRecord of data * **String** (String) - Required - Comma-delimited string of fieldnames ### Returns #### Success Response * **Void** - Field objects will be added to data ### Request Example ```javascript (function($sp) { var gr = new GlideRecord("tablename"); var fieldnames = "sys_id,field_name"; $sp.getRecordElements(data, gr, fieldnames); })($sp); ``` ``` -------------------------------- ### g_form API: Get Decimal Value Source: https://serviceportal.io/docs/documentation/client_scripting.md Retrieves the decimal value of a field. Useful for currency or precise number fields. ```javascript g_form.getDecimalValue(fieldName) ``` -------------------------------- ### format Source: https://serviceportal.io/docs/documentation/widget_client_script_apis.md Provides an alternative to string concatenation for building strings with variables. ```APIDOC ## format(String, Object) ### Description Alternative to string concatenation. Allows building strings with variables using placeholders. ### Method Signature `spUtil.format(template, data)` ### Parameters * **template** (String) - The string template containing placeholders (e.g., `{variableName}`). * **data** (Object) - An object containing key-value pairs where keys match the placeholder names in the template. ### Request Example ```javascript spUtil.format('An error ocurred: {error} when loading {widget}', {error: '404', widget: 'sp-widget'}) ``` ``` -------------------------------- ### $sp.getRecord Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Retrieves the GlideRecord for the current widget instance. ```APIDOC ## $sp.getRecord ### Description Returns the GlideRecord for the current sp_instance*. Returns null if the widget is embedded by another widget. ### Method $sp.getRecord() ``` -------------------------------- ### Check Desktop vs Mobile Runtime Source: https://serviceportal.io/docs/documentation/client_scripting.md Use this to conditionally execute code based on whether the script is running in a mobile or desktop environment. The 'window' object is null in the mobile runtime. ```javascript if (window === null) // Write your mobile compatible code here else // Write your desktop compatible code here ``` -------------------------------- ### $sp.getRecordElements Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Copies field values and display values from a GlideRecord into the data parameter. ```APIDOC ## $sp.getRecordElements ### Description Copies the value and display value for the specified field names from a GlideRecord into the data parameter. ### Method $sp.getRecordElements(Object, GlideRecord, String) ### Parameters - **Object** (data) - The data object to populate. - **GlideRecord** - The source GlideRecord. - **String** (field names) - A comma-separated string of field names. ``` -------------------------------- ### $sp.getForm Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Retrieves form information for a given table and sys_id. ```APIDOC ## $sp.getForm ### Description Returns the form. ### Method $sp.getForm(String table, String sys_id, /_Optional String_ / encodedQuery, /_Optional String_ / view) ### Parameters - **String** (table) - The name of the table. - **String** (sys_id) - The sys_id of the record. - **Optional String** (encodedQuery) - An encoded query to filter records. - **Optional String** (view) - The view to use for the form. ``` -------------------------------- ### $sp.getValues (sp_instance) Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Copies values from the widget's sp_instance GlideRecord into the data parameter. ```APIDOC ## $sp.getValues (sp_instance) ### Description Copies values from the widget's sp_instance GlideRecord into the data parameter. ### Method $sp.getValues(Object) ### Parameters - **Object** (data) - The data object to populate. ``` -------------------------------- ### $sp.getValues (request/instance) Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Copies values from the request or instance into the data parameter. ```APIDOC ## $sp.getValues (request/instance) ### Description Copies values from the request or instance into the data parameter. ### Method $sp.getValues(Object, String) ### Parameters - **Object** (data) - The data object to populate. - **String** (field names) - A comma-separated string of field names. ``` -------------------------------- ### $sp.getMenuItems Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Retrieves the menu items associated with a specific menu instance. ```APIDOC ## $sp.getMenuItems ### Description Returns the menu items for the specified instance. ### Method $sp.getMenuItems(String) ### Parameters - **String** (sys_id) - The sys_id of the sp_instance record for the menu. ``` -------------------------------- ### Display Info Message with spUtil Source: https://serviceportal.io/docs/documentation/widget_client_script_apis.md Use to display a notification info message to the user. Accepts a string message. ```javascript spUtil.addInfoMessage("Your order has been placed") ``` -------------------------------- ### Provide Widget Options in HTML Source: https://serviceportal.io/docs/documentation/widget_embedded.md Pass options to an embedded widget directly within the HTML template using the `options` attribute. Options are provided as a JSON string. ```HTML ``` -------------------------------- ### $sp.getListColumns Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Retrieves a list of columns for a given table and view. ```APIDOC ## $sp.getListColumns ### Description Returns a list of the specified table's columns in the specified view. ### Method $sp.getListColumns(String tableName, String view) ### Parameters - **String** (tableName) - The name of the table. - **String** (view) - The name of the view. ``` -------------------------------- ### $sp.getField Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Retrieves detailed information about a specific field on a GlideRecord. ```APIDOC ## $sp.getField ### Description Returns {display_value, label, type, value} for a given field on a GlideRecord. ### Method $sp.getField(GlideRecord, String) ### Parameters - **GlideRecord** - The GlideRecord object. - **String** (field name) - The name of the field. ``` -------------------------------- ### $sp.logStat Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Creates a new entry in the sp_log table to track events like searches or page visits. ```APIDOC ## $sp.logStat ### Description Create a new entry in the `sp_log` table with a table name, a record sys_id from that name, and some type and optional comments. Handy for doing things like logging searches or visits to pages, etc. ### Method $sp.logStat(String type, String table, String id, _opt String comments_) ### Parameters - **String** (type) - The type of statistic to log. - **String** (table) - The name of the table. - **String** (id) - The sys_id of the record. - **Optional String** (comments) - Additional comments for the log entry. ``` -------------------------------- ### Embed Multiple Widgets with Custom Options Source: https://serviceportal.io/docs/documentation/widget_embedded.md Demonstrates embedding multiple instances of the same widget with different configurations. The HTML template uses `ng-repeat` to iterate over data prepared in the server script. ```HTML
Time across the US
``` ```CSS .panel { margin-top: 10px; } ``` ```JavaScript function() { // nothing to do here... } ``` ```JavaScript (function() { var options = [ {zone: "America/Los_Angeles", title: "San Diego"}, {zone: "America/Denver", title: "Denver"}, {zone: "America/Chicago", title: "Chicago"}, {zone: "America/New_York", title: "New York"} ]; data.clocks = []; for (var i in options) { data.clocks.push($sp.getWidget("widget-cool-clock", options[i])); } })(); ``` -------------------------------- ### refresh Source: https://serviceportal.io/docs/documentation/widget_client_script_apis.md Calls the server to refresh the current widget's options and data. Returns a Promise. ```APIDOC ## refresh(Object $scope) ### Description Calls the server and automatically replaces the current options and data from the server response. Returns a Promise. This is similar to `server.refresh()`, but allows specifying a `$scope`. ### Method Signature `spUtil.refresh($scope)` ### Parameters * **$scope** (Object) - The scope object to pass to the server call. ### Returns A Promise that resolves when the refresh is complete. ``` -------------------------------- ### $sp.getSCRecord Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Retrieves the sc_cat_item record for the portal's catalog. ```APIDOC ## $sp.getSCRecord ### Description Returns sc_cat_item record for the portal's catalog with sys_class_name != sc_cat_item_wizard and active = true in the query. GlideRecord returned has not yet triggered the query. ### Method $sp.getSCRecord() ``` -------------------------------- ### g_form API: Add Decoration Source: https://serviceportal.io/docs/documentation/client_scripting.md Adds an icon and tooltip to a field for visual cues. Ensure the icon is available in the system. ```javascript g_form.addDecoration(fieldName, icon, title) ``` -------------------------------- ### $sp.canReadRecord Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Checks if the current user has read permissions for a given GlideRecord. ```APIDOC ## $sp.canReadRecord ### Description Returns true if the user can read the specified GlideRecord. ### Method $sp.canReadRecord(Mixed, _opt String_) ### Parameters - **Mixed** (GlideRecord or sys_id) - The record to check. - **_opt String_** (Optional) - The table name if the first parameter is a sys_id. ``` -------------------------------- ### Embed Widget Client-Side using spUtil Source: https://serviceportal.io/docs/documentation/widget_embedded.md Embed a widget client-side by using the `spUtil.get()` method in your client script. The widget model is then assigned to a scope variable. ```HTML ``` ```JavaScript function(spUtil) { var c = this; spUtil.get("widget-cool-clock").then(function(response) { c.myClockWidget = response; }); } ``` -------------------------------- ### GlideRecord: Query (Callback) Source: https://serviceportal.io/docs/documentation/client_scripting.md Executes the GlideRecord query asynchronously and processes the results using a callback function. ```javascript new GlideRecord(tableName).query(callback) ``` -------------------------------- ### update Source: https://serviceportal.io/docs/documentation/widget_client_script_apis.md Calls the server, sending the current `this.data` to the server. Returns a Promise. ```APIDOC ## update(Object $scope) ### Description Calls the server and `this.data` is automatically sent to the server side. Returns a Promise. This is similar to `server.update()`, but allows specifying a `$scope`. ### Method Signature `spUtil.update($scope)` ### Parameters * **$scope** (Object) - The scope object to pass to the server call. ### Returns A Promise that resolves when the update is complete. ``` -------------------------------- ### $sp.getStream Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Retrieves the activity stream for a specific record. ```APIDOC ## $sp.getStream ### Description Get the activity stream for a record. ### Method $sp.getStream(String, String) ### Parameters - **String** (table name) - The name of the table. - **String** (sys_id) - The sys_id of the record. ``` -------------------------------- ### Interact with Glide Platform using RESTMessage Source: https://serviceportal.io/docs/documentation/widget_server_script.md Use this snippet to interact with external services like Yahoo Finance by making REST calls. Ensure the 'Yahoo Finance' REST Message is configured in your ServiceNow instance. The `input` object must contain a `symbol` property. ```javascript if (input) { var r = new RESTMessage('Yahoo Finance', 'get'); r.setStringParameter('symbol', input.symbol); var response = r.execute(); data.price = response.getBody(); } ``` -------------------------------- ### g_service_catalog API Source: https://serviceportal.io/docs/documentation/client_scripting.md The g_service_catalog API provides utility methods for Service Catalog interactions. ```APIDOC ## g_service_catalog API ### Description Provides utility methods for Service Catalog interactions. ### Methods - isOrderGuide() ``` -------------------------------- ### GlideRecord: Insert Record (Callback) Source: https://serviceportal.io/docs/documentation/client_scripting.md Inserts a new record into the table asynchronously. Requires a callback function. ```javascript new GlideRecord(tableName).insert(callback) ``` -------------------------------- ### $sp.getRecordDisplayValues Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Copies display values for specified fields from a GlideRecord into the data parameter. ```APIDOC ## $sp.getRecordDisplayValues ### Description Copies display values for the specified field names from a GlideRecord into the data parameter. ### Method $sp.getRecordDisplayValues(Object, GlideRecord, String) ### Parameters - **Object** (data) - The data object to populate. - **GlideRecord** - The source GlideRecord. - **String** (field names) - A comma-separated string of field names. ``` -------------------------------- ### g_form API: Set Field Placeholder Source: https://serviceportal.io/docs/documentation/client_scripting.md Sets a placeholder text for an input field, visible when the field is empty. ```javascript g_form.setFieldPlaceholder(fieldName, placeholder) ``` -------------------------------- ### Registering a Record Watch Listener in Client Script Source: https://serviceportal.io/docs/documentation/widget_record_watch.md Use spUtil.recordWatch to listen for updates on a specific table with a given filter. Ensure $scope is injected into your Client Script function. ```javascript function(spUtil, $scope) { /* widget controller */ var c = this; spUtil.recordWatch($scope, "incident", "active=true", function(name, data) { console.log(name); //Returns information about the event that has occurred console.log(data); //Returns the data inserted or updated on the table }); } ``` -------------------------------- ### Display Trivial Message with spUtil Source: https://serviceportal.io/docs/documentation/widget_client_script_apis.md Use to display a brief, non-critical notification message to the user. Accepts a string message. ```javascript spUtil.addTrivialMessage("Thanks for your order") ``` -------------------------------- ### $sp.getParameter Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Retrieves a parameter value from the query string or POST body. ```APIDOC ## $sp.getParameter ### Description Returns the value of a given key from the query string or post body. ### Method $sp.getParameter(String) ### Parameters - **String** (key) - The name of the parameter to retrieve. ``` -------------------------------- ### GlideRecord: Add Order By Source: https://serviceportal.io/docs/documentation/client_scripting.md Adds an ascending sort order to the query results based on the specified field. ```javascript new GlideRecord(tableName).addOrderBy(fieldName) ``` -------------------------------- ### $sp.saveRecord() Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Saves or updates the current record associated with the widget instance. ```APIDOC ## $sp.saveRecord() ### Description Saves or updates the current record. ### Method Unknown ### Parameters None ### Response Unknown ``` -------------------------------- ### addInfoMessage Source: https://serviceportal.io/docs/documentation/widget_client_script_apis.md Displays a notification info message to the user. ```APIDOC ## addInfoMessage(String message) ### Description Displays a notification info message. ### Method Signature `spUtil.addInfoMessage(message)` ### Parameters * **message** (String) - The info message to display. ### Request Example ```javascript spUtil.addInfoMessage("Your order has been placed") ``` ``` -------------------------------- ### Check Record Read Access - Server Script Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Determines if the current user can read a specific record or if a record is valid. For certain tables like kb_knowledge, sc_cat_item, or sc_category, it also verifies view access. ```javascript data.items = []; data.userName = gs.getUserDisplayName(); var gr = new GlideRecord("sc_cat_item"); gr.query(); while(gr.next() && data.items.length < 10) { if ($sp.canReadRecord(gr)) { data.items.push(gr.getDisplayValue("name")); } } ``` -------------------------------- ### $sp.canReadRecord() Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Checks if a record is valid and if the logged-in user has permission to access it. For specific record types, it also checks view permissions. ```APIDOC ## $sp.canReadRecord(gr | table, sys_id) ### Description Useful for quickly determining if a record is valid and if the logged-in user has access to it. > If the record type is kb_knowledge, sc_cat_item, or sc_category it also checks if the user can view that item. ### Method Signatures 1. `$sp.canReadRecord( gr ): Boolean` 2. `$sp.canReadRecord( table, sys_id ): Boolean` ### Parameters #### For `$sp.canReadRecord( gr )`: * **gr** (_GlideRecord_) - A glide record #### For `$sp.canReadRecord( table, sys_id )`: * **table** (_String_) - A table name to query. * **sys_id** (_String_) - The record sys_id to query. ### Returns * (_Boolean_) True if the record is valid and readable. ``` -------------------------------- ### g_form API: Set Value Source: https://serviceportal.io/docs/documentation/client_scripting.md Sets the value of a specified field. Optionally provide a display value for reference fields. ```javascript g_form.setValue(fieldName, value, displayValue) ``` -------------------------------- ### Watch Table Updates with spUtil Source: https://serviceportal.io/docs/documentation/widget_client_script_apis.md Monitors a specific table for updates based on a filter. Executes a callback function when a relevant change occurs. Requires the scope, table name, and filter criteria. ```javascript spUtil.recordWatch($scope, "live_profile", "sys_id=" + liveProfileId); ``` -------------------------------- ### GlideRecord API Source: https://serviceportal.io/docs/documentation/client_scripting.md The GlideRecord API allows client-side scripting to query and manipulate records in the database. ```APIDOC ## GlideRecord API ### Description Allows client-side scripting to query and manipulate database records. ### Constructor - new GlideRecord(tableName) ### Methods - addQuery(encodedQuery) - addQuery(fieldName, operator, value) - getEncodedQuery() - deleteRecord(callback) - get(id) - getTableName() - hasNext() - insert(callback) - gotoTop() - next() - loadRow(rowObj) - getValue(fieldName) - setValue(fieldName, value) - isDotWalkField(fieldName) - addOrderBy(fieldName) - orderBy(fieldName) - orderByDesc(fieldName) - setDisplayFields(fieldNames) - query(callback) - setRows(rowsArray) - setTableName(tableName) - update(callback) - setLimit(maxInt) - getLimit() ``` -------------------------------- ### GlideRecord: Order By (Ascending) Source: https://serviceportal.io/docs/documentation/client_scripting.md Specifies an ascending sort order for the query results. ```javascript new GlideRecord(tableName).orderBy(fieldName) ``` -------------------------------- ### Translate Strings in HTML Template Source: https://serviceportal.io/docs/documentation/widget_internationalization.md Use ${message} syntax directly in HTML templates for simple string internationalization. This is a shorthand for gs.getMessage(). ```HTML

${This message will be internationalized.}

However, this will NOT be.

``` -------------------------------- ### $sp.getDisplayValue() Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Returns the display value of a specified field from either the widget's sp_instance or the sp_portal record. It first checks the sp_instance record and then the sp_portal record if the field is not found or empty on the instance. ```APIDOC ## $sp.getDisplayValue() ### Description Returns the display value of a given field (if it exists and has a value) from either the widget's sp_instance or the sp_portal record. Refer to the following diagram: This map visualizes a service portal page with one widget on it. Calling $sp.getDisplayValue("title") would return the display value of the title field on the widget's sp_instance record. If the title field didn't exist or was empty, then it would try the same operation on the the sp_portal record for the current portal context. > Note - Embedded widgets do not have sp_instance records. ### Method $sp.getDisplayValue( fieldName ) ### Parameters #### Path Parameters * **fieldName** (String) - The field name to get the display value of. ### Returns #### Success Response * **String** - A display value from either the sp_instance record or sp_portal record. ### Request Example ```javascript (function() { data.title = $sp.getDisplayValue("title"); data.catalog = $sp.getDisplayValue("sc_catalog"); })(); ``` ``` -------------------------------- ### g_form API: Add Info Message Source: https://serviceportal.io/docs/documentation/client_scripting.md Displays an informational message to the user, typically at the top of the form. ```javascript g_form.addInfoMessage(message) ``` -------------------------------- ### Display Error Message with spUtil Source: https://serviceportal.io/docs/documentation/widget_client_script_apis.md Use to display a notification error message to the user. Accepts a string message. ```javascript spUtil.addErrorMessage("There has been an error processing your request") ``` -------------------------------- ### Set Glide List Filter and Items Source: https://serviceportal.io/docs/documentation/client_scripting.md Use g_list.get() to retrieve a glide list element and then reset, set the query, and add items. This API replaces g_filter on desktop client scripts. ```javascript function onLoad() { var myListCollector = g_list.get("my_list_collector"); myListCollector.reset(); myListCollector.setQuery("active=true^category=8c7b22230b402200b0b02c6317673a62"); myListCollector.addItem('3a700d39af5f4fc0aab978df90f4c692', 'Power Supply'); myListCollector.addItem('1cb93419a3a248318da8f814140b42f6', 'Backpack'); } ``` -------------------------------- ### $sp.getFieldsObject Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Retrieves an object containing valid field names from a GlideRecord. ```APIDOC ## $sp.getFieldsObject ### Description Checks the specified field names, and returns an object containing the valid names. ### Method $sp.getFieldsObject(GlideRecord, String) ### Parameters - **GlideRecord** - The GlideRecord object. - **String** (field names) - A comma-separated string of field names to check. ``` -------------------------------- ### g_form API: Show Field Message Source: https://serviceportal.io/docs/documentation/client_scripting.md Displays a message (info or error) for a specific field, optionally scrolling the form to it. ```javascript g_form.showFieldMsg(fieldName, message, type: "info | error", scrollForm) ``` -------------------------------- ### GlideRecord: Go to Top Source: https://serviceportal.io/docs/documentation/client_scripting.md Resets the GlideRecord cursor to the first record in the result set. ```javascript new GlideRecord(tableName).gotoTop() ``` -------------------------------- ### $sp.getValue() Source: https://serviceportal.io/docs/documentation/widget_server_script_apis.md Retrieves the value of a specified field from either the widget's sp_instance or the sp_portal record. It returns the value if it exists and is not empty. ```APIDOC ## $sp.getValue() ### Description Returns the value of a given field (if it exists and has a value) from either the widget's sp_instance or the sp_portal record. ### Method Signature `$sp.getValue(fieldName)` ### Parameters #### Path Parameters - **fieldName** (String) - Required - The name of the field to retrieve the value of. ### Returns - **Object** - A value from either the sp_instance record or sp_portal record. ``` -------------------------------- ### g_form API: Submit Form Source: https://serviceportal.io/docs/documentation/client_scripting.md Submits the form, triggering onSubmit client scripts. Specify an optional submit action name. ```javascript g_form.submit(submitActionName) ```