Ashley Snyder
ServiceNow Employee
ServiceNow Employee
 Center of Excellence / Workspace / How to use UI Actions in Workspace

 

FYI: This article has not been updated or reviewed since the Tokyo release. Use at your discretion, but be advised that these methods may or may not work on later releases.

 

 

Table of Contents


Overview
Fields and Tables
Call a Server Side UI Action
Unsupported Methods
Methods
GlideAgentWorkspace
g_modal
Show Fields
Show Frame
Alert
Confirm
Confirm Destroy
action.openGlideRecord
Community Resources

 
 

Overview

 

UI Actions are supported in both agent and configurable workspaces, but only in limited areas, such as the Action Bar component which is provided by default on the out-of-the-box record page. This means that UI Actions are only supported on forms in workspaces and not lists. If you have existing UI Actions on forms that you want to port over to your workspace or need to use the same UI Action on both a workspace and in the classic environment, you may be able to modify your UI Action code to do so. The Set up custom UI actions in legacy workspace product documentation has extensive information on creating UI Actions, and most of the information does still apply to both configurable and agent workspaces.

You can use Declarative Actions in the workspace ui on forms, lists, and related lists, and they work with both workspaces and UI Builder pages, so you don’t need to customize an out-of-the-box UI Builder page. For more information see our COE article on Declarative Actions.

 

Fields and Tables

 

There are some main fields and tables you need to know to use UI Actions in configurable workspaces. When using Workspace options ensure the Client checkbox on the UI Action is set to true.

 

  • Workspace Form Button - To make the UI Action appear on the list of UI Actions.
  • Workspace Form Menu - To make the UI Action appear as a list item in the menu associated with UI Actions.
  • Workspace Client Script - This is an optional field used to create a workspace-specific client script. Workspace has similar client scripting limitations as Service Portal.
  • Format for Configurable Workspace (Available in San Diego) - Automatically creates the UX Form Action record needed to link the UI Action to configurable workspaces.
  • UX Form Action - Links a UI Action to use in configurable workspaces.
 

Call a Server Side UI Action

 

Workspaces use client-side UI Actions, and a UI Action must be marked as Client in order for it to appear and function on a workspace. So what do you need to do if you want to re-use a server-side UI Action you've previously created or want to create in a workspace UI Action? You have some choices. You can create a server script Declarative Action for the Workspace, which is detailed in our COE article on Declarative Actions, or you could call the server-side UI Action from your client-side UI Action.

 

Example

 

 

function onClick() {
  var actionName = g_form.getActionName();
  g_form.submit(actionName);
}

 

 

 

 

Unsupported Methods

 

The workspace client scripting environment does not support the following global variables:

  • this, window, document
  • $, $$, jQuery, $j
  • angular

In general, accessing globals is not behavior that should be relied upon. The client scripts should only access the registered objects i.e. documented client side methods within the scripting environment.

 

Methods

 

GlideAgentWorkspace

This is a documented API, for more information on the methods see the documentation on the developer site. The g_aw API enables a UI Action or Client Script to open a specified record in a Workspace tab. Two methods are currently available, see the Close tab and save-and-close tab UI Actions product documentation for specific examples.

closeRecord()

openRecord()

You can also try the undocumented setSectionExpanded method to collapse or expand your sections.

 

Example

 

 

g_aw.setSectionExpanded('Notes', false); // will collapse the Notes section
g_aw.setSectionExpanded('Resolution', true); // will expanded the Resolution section

 

 

 

 

g_modal

A client scriptable API that allows the user to display an overlaid modal window and perform the following:

  • Display input type fields in a modal window
  • Show something else in a frame such as a UI Page or external link
  • Perform action on confirm
  • Load a component

 

Common Properties for Methods

title: The title of the Modal window

size: The size of the Modal window: sm, lg, xl, fw (fixed-width)

height: Height of the Modal window in pixels/em (optional)

 

 

showFields

A g_modal method that displays a modal window with the fields defined in the UI Action Workspace Client Script. Displays the OK and Cancel buttons by default. 

 

Properties

Accepts title, message, and callback as arguments and returns a promise. The fields property is required. If only one argument has been provided it will be treated as a fields parameter.

fields:

name: The name of the field, if using a reference field it is the name of the reference field on the form

type: textarea, choice, reference, boolean, string

label: How the field displays to the user

value: Initial value of the field, useful in choices or booleans

mandatory: true or false

 

If type is reference:

name: The reference field on the current record being used to search

reference: The table you're referencing

referringTable: The table you're referencing from

referringRecordId: The sys_id of the value you're calling in the UI Action form

value: Can use the g_form method here to get the value

displayValue: Display value must be used in conjunction with value

 

 

Example 

This is a simple example of prompting a user for a reason using a modal window, and then passing it back to the Work notes field on the record. In the example below the then() method returns a Promise, which returns what the modal returns such as fieldValues in this example. In this example the work notes field on the client side with the field value are in the updatedFields array. Since only one field is being returned, the index/position was 0. If returning multiple fields just enter the position they are in.

 

 

 

 

function onClick(g_form) {
    g_modal.showFields({
        title: "Enter your reason",
        fields: [{
            type: 'textarea',
            name: 'work_notes',
            label: getMessage('Reason'),
            mandatory: true
        }],
        size: 'lg'
    }).then(function(fieldValues) {
        g_form.setValue('work_notes', fieldValues.updatedFields[0].value);
        g_form.save();
    });
}

 

 

 

 find_real_file.png

 

This example expands on using more fields, such as a choice field and a reference field.

 

 

 

function onClick(g_form) {

    var fields = [{
        type: 'textarea',
        name: 'work_notes',
        label: getMessage('Reason'),
        mandatory: true
    },
        {
            type: 'choice',
            name: 'reason_code',
            label: getMessage('Reason code'),
            value: getMessage(' -- Select -- '),
            choices: [{
                displayValue: 'Duplicate',
                value: 'duplicate'
            },
                {
                    displayValue: 'Canceled',
                    value: 'canceled'
                }
            ],
            mandatory: true
        },
        {
            type: 'reference',
            name: 'caller_id',
            label: getMessage('What is your name?'),
            mandatory: true,
            reference: 'sys_user',
            referringTable: 'incident',
            referringRecordId: g_form.getUniqueValue(),
			value: g_form.getValue('caller_id'),
			displayValue: g_form.getDisplayValue('caller_id')
        }
    ];

    g_modal.showFields({
        title: "Enter your reason",
        fields: fields,
        size: 'lg'
    }).then(function(fieldValues) {
        g_form.setValue('work_notes', fieldValues.updatedFields[0].value);
        g_form.setValue('caller_id', fieldValues.updatedFields[2].value);
        g_form.save();
    });
}

 

 

 

 

find_real_file.png

 

showFrame

A g_modal method to link to external URLs or UI Pages. 

 

Properties

Accepts a title, message, and callback. The url property is mandatory. If only one property is provided it will be treated as a url parameter.

 

Example 

 

 

function onClick(g_form) {
    var kbId = '24d9243187032100deddb882a2e3ec33'; //sysId of KB article
    g_modal.showFrame({
        url: '/kb_view.do?sys_kb_id=' + kbId,
        title: 'Test Knowledge Article',
        size: 'lg',
        height: 500
    });
}

 

 

 

 

find_real_file.png

 

The next example is using a UI Page embedded and uses window.parent.postMessage() in the UI Page to pass data from the iFrame back to the workspace since g_form is not accessible in the UI Page when it is in the iFrame. In your instance or PDI the Propose Major Incident UI Action is a great resource to see how UI Pages are being called in workspaces.

 

 

 

function onClick(g_form) {
	function proposeMIC(data) {
		var workNotes = data.msg + "\n" + data.workNotes;
		var notes = g_form.getValue('work_notes') + ' ' + workNotes;
		var bi = g_form.getValue('business_impact') + ' ' + data.businessImpact;
		g_form.setValue('work_notes', notes.trim());
		g_form.setValue('business_impact', bi.trim());
		g_form.submit('sysverb_mim_propose');
	}
	
	function openPopup() {
		if(!g_form.getControl('work_notes')) {
			getMessage('Cannot propose major incident as "Worknotes" is not visible', function(msg) {
				g_form.addErrorMessage(msg);
			});
			return false;
		}

		var url = "/sn_major_inc_mgmt_mim_propose.do?sysparm_stack=no&sysparm_workspace=" + true;
		g_modal.showFrame({
			title: getMessage("Propose Major Incident"),
			url: url,
			size: 'lg',
			autoCloseOn: 'URL_CHANGED',
			callback: function (ret, data) {
				if (ret)
					proposeMIC(data);
			}
		});
	}
	
	openPopup();
}

 

 

 

In the UI Page within the Client Script the following function is being used to handle the Cancel that you may need to use in your UI Pages as the native Cancel functionality does not work. The config to identify the workspace is set in the HTML.

 

 

 

var config = {workspace: '${JS_STRING:RP.getParameterValue('sysparm_workspace')}' == 'true'};

function close() {
    if(!config.workspace)
        dialog.destroy();
    else
        window.location.href = window.location.href + '&sysparm_next_pg=true';
}

 

 

 

Also, if you log the data object it will return the following:

 

 

 

data: {"msg":"Proposed as major incident candidate","workNotes":"work note note","businessImpact":"business impact note"}

 

 

 

 

find_real_file.png

Alert

Displays an alert to the user when performing an action. See the Confirm example below as an alert is displayed to the message if the user does not meet the requirements.

 

Properties

Accepts title, message, and callback as arguments and returns a Promise. Message is required, if only one argument has been provided it will be treated as a message parameter.

alert: getMessage(Title of the Modal), msg(Text to the user), callback

 

Confirm

Displays a confirmation to the user when performing an action.

 

Properties

Accepts title, message, and callback as arguments and returns a Promise. Message is required, if only one argument has been provided it will be treated as a message parameter.

confirm: getMessage(Title of the Modal), msg(Text to the user), callback

 

Example 

This example is adopted from the End Chat UI Action on an Interaction, and is a good example of using if statements to determine when a user can take an action and performing the action when the user clicks OK versus Cancel for example setting the state of the record to Closed.

 

 

 

function onClick(g_form) {

    if (g_user.userID != g_form.getValue('assigned_to')) {
        g_modal.alert('Only the assigned to can end this action.');
        return;
    }

    var msg = getMessage("Are you sure you want to take this action?");
    g_modal.confirm(getMessage("Confirmation"), msg, function (confirmed) {
        if (confirmed) {
            g_form.setValue('state', 'closed_complete');
            g_form.save();
        }
    });

    return false;
}

 

 

 

 

find_real_file.png

 

Confirm Destroy

Similar to the Confirm method, except the confirm button is show as a destructive style. 

 

Properties

Accepts title, message, and callback as arguments and returns a Promise. Message is required, if only one argument has been provided it will be treated as a message parameter.

confirmDestroy: getMessage(Title of the Modal), msg(Text to the user), callback

 

action.openGlideRecord

This is another documented API that is very handy when using UI Actions in workspaces. Instead of using action.setRedirecrURL in the UI Action, action.openGlideRecord can be used instead, and will work for both platform and workspace. 

Example

The following example is a simple server script with the Workspace Form Button and Format for Configurable Workspace options selected. Upon clicking the button the server script will run and open the new record in a sub-tab.

 

 

 

var incGr = new GlideRecord('incident');
incGr.newRecord();
incGr.setValue('caller_id', current.getValue('contact'));
incGr.setValue('short_description', current.short_description);
incGr.insert();
action.openGlideRecord(incGr);

 

 

 

 

find_real_file.png

 

Community Resources

 

We’ll link community articles that use the methods mentioned above as we find them. If you think an article should be listed here please comment.

Replicate choice field on Workspace modal with g_modal by Aare Pujuste

Comments
smitaD
Tera Contributor

Hi @Sid_Takali 

you can use this code 

 var selectedAccount = g_form.getValue('account');
 var contactField = {
        type: 'reference',
        name: 'contact',
        label: getMessage('Contact'),
        mandatory: false,
        reference: 'sys_user',
        referringTable: 'incident',
        referringRecordId: g_form.getUniqueValue(),
        id: 'custcontact',
        filter: 'account=' + selectedAccount,
    };
Community Alums
Not applicable

@Ashley Snyder 
@Ashley Snyder 

Hi All,
THE MOTO IS TO  open a catalog in new window and for that catalog need to submit the request.

 

Please find my Ui action details and code below:

UI action name: Create ICMS Ticket

Active: true

client: true

Onclick: onClickIcms()();

Workspace Form button: true

HemantAggarwal_0-1726747267717.png

 

 


Workspace Client Script//I have wrote the script here as I was not able to execute in on workspace when written in Script section too

function onClickIcms() {
var url = "/" + "sp?id=sc_category&sys_id=354d31471b774a9058b4744a9b4bcbaf&catalog_id=2d8cb1071b774a9058b4744a9b4bcb19&spa=1";
gsftSubmit(null, g_form.getFormElement(), 'create_icms_ticket');
top.window.open(url, '_blank');
}
if (typeof window == 'undefined') case_map();

function case_map() {
var getCase = current.sys_id;
var session = gs.getSession();
session.putClientData('caseID', getCase);
action.setRedirectURL(current);
}

Kindly suggest on how can we get this working.

 

Thanks in advance.

Hiranmayee Moha
Tera Expert

Hi @Ashley Snyder !

 

How to hide or grey out "reassign" button from the record information tab for "resolved incidents" in the contextual sidebar SOW?

 

Thanks in advance!

tiguin2798
Tera Guru

I know this is an old thread, but I want to share a link to a post where I was having a similar issue with using 'g_modal.showFields' and not being able to have an action on the cancel button in the Modal. Going through multiple articles and UI pages trying to find the setup for this....a workaround and solution is to use the catch function.

I hope this can help someone!

https://www.servicenow.com/community/developer-forum/how-to-convert-glide-prompt-to-workspace-dialog...

Angelo Paulo Ad
Tera Contributor

Asking around here since I can't really understand what is the g_modal.showFrame equivalent for passing values to the UI Page in workspace?

 

With setPreference then you pass it to the UI page.

 

Amanda de Olive
Tera Expert

An option for UI Action worskpace with a single button and scratchpad

 

AmandadeOlive_0-1738090531725.png

AmandadeOlive_2-1738090690760.png

 

function onClick(g_form) {
    var msg = g_scratchpad.comment;
    g_modal.alert(getMessage("My title"), msg, function() {
    });
}

 

ShuRiseUp2023
Tera Expert

Hi @Ashley Snyder.   It's a very helpful article. Thank you for sharing. Now I'm wondering is it possible to show/hide a field based on another field's value. For example, rejection reason is 'Other', then show the other details String field. Otherwise hide the other details field. 

Another question, is it possible the call a script include to fetch the choices from sys_choice table. For example, the rejection reason field's choices of the custom table. So, the choices will not be hardcoded and changes if more choices added into that field. 

Thank you so much! 

Jithender1
Tera Contributor

Hello @Ashley Snyder  

 

Can you please help me out on this.

 

we have created a button on platform UI which will call script include.

need the same to replicate in workspace but unable to do so.

 

UI action script for platform ui:

 

function onClick() {

    var additionalusers = g_form.getValue('additional_affected_user_required');
    //var affectedusers = g_form.getValue('additional_affected_user');

    if (additionalusers == 'false') {
        alert("Alert : this is test");
        return;
    }
    var gm = new GlideModal("glide_confirm_basic"true600);
    gm.setTitle("Disable Confirmation");
    gm.setPreference("title"" Warning : .Are you sure you want to disable their accounts?");
   
    gm.setPreference("onPromptComplete"function() {
        alert('clicked ok');
        gsftSubmit(null, g_form.getFormElement(), 'demo_user');
        var ga = new GlideAjax('Disable_User');
        ga.addParam('sysparm_name''updateAccount');
        ga.addParam('sysparm_incident_id', g_form.getUniqueValue());
        ga.getXMLAnswer(function(response) {
            
            gsftSubmit(null, g_form.getFormElement(), 'demo_user');
           
        });
    });

    gm.setPreference("onPromptCancel"function() {
        alert("You clicked on 'Cancel'");
    });
    gm.render();
}
 
Need same functionality in workspace button as well. Please help.
 
Note: confirm() method is not working in our environment, please use glide_modal_confirm as above.
Jeff Wentworth
ServiceNow Employee
ServiceNow Employee

Hi @Ashley Snyder, any plans to update this article for Xanadu to present?

 

This is a fantastic, detailed, and extremely helpful article.

 

Thanks,

-- Jeff

Deepak Negi
Mega Sage
Mega Sage

How do we add an error message in the modal body.
I know there is an 'instruction' attribute which allows to pass any text in the modal but is there a way to style that in any given color e.g blue for information, red for error etc

AmolJ
Tera Expert

This is just so hard. UI Action button doesn't work. What do I need to have in the "Action Name" and "OnClick" fields?

Version history
Last update:
‎09-26-2023 06:33 AM
Updated by:
Contributors