Service Now - UI Action on Related List

Monday Mar 9, 2020

We can use UI actions for lots of things, and UI actions on related lists can be very useful as well.

Often, we need to get the “parent” of the related list in the UI action, and if we are server-side we have to use the undocumented action object that is automagically set for the UI Action

var uri = action.getGlideURI();
uri.get('sysparm_collection_key'); // Field name of relation
uri.get('sysparm_collectionID'); // sys_id of parent record

If we are using client UI actions we can do it one of two ways:

g_form.getUniqueValue();

// Or via g_list:

g_list.getSubmitValue('sysparm_collection_key'); // Field name of relation
g_list.getSubmitValue('sysparm_collectionID'); // sys_id of parent

A note on the example

Just a quick note on the example below - it is bad to have this much duplicate code in 2 places.

The only difference is the value we are setting on the object.

We should create a Script Include to share the code

Code

A good practical use of this is to have several UI actions that preset some values on your related list item to drive the form layout.

Let’s say we have a short_form and long_form form layout for a related list item.

We want to select the layout based on the form_type field of the of the item.

We can create 2 *View Rule*s to say that when our item has short_form in the form_type field we render the short_form form view, and vice-versa for the lsong_form in the form_type field.

Then, we create 2 UI actions to create & set the form_type and setup the redirect/back URLs:

### Short form UI action

    // Get parent ID from URI
    var uri = action.getGlideURI();
    var parentItemId = uri.get('sysparm_collectionID'); 
    
    // Create our new record and set the field that determines the form view
    var gr = new GlideRecord('xyz_related_list_table')
    gr.initialize();
    gr.setValue('form_type', 'short_form');
    
    // Redirect to edit the new item 
    action.setRedirectURL(gr);
    
    // When the user submits the new item or goes back go back
    // to the parent item.
    var parentRecord = new GlideRecord('xyz_parent_table');
    parentRecord.get(parentItemId);
    action.setReturnURL(parentRecord);

 

Long form UI action

    // Get parent ID from URI
    var uri = action.getGlideURI();
    var parentItemId = uri.get('sysparm_collectionID'); 
    
    // Create our new record and set the field that determines the form view
    var gr = new GlideRecord('xyz_related_list_table')
    gr.initialize();
    gr.setValue('form_type', 'long_form');
    
    // Redirect to edit the new item 
    action.setRedirectURL(gr);
    
    // When the user submits the new item or goes back go back
    // to the parent item.
    var parentRecord = new GlideRecord('xyz_parent_table');
    parentRecord.get(parentItemId);
    action.setReturnURL(parentRecord);