Reload a Form or Related list from a Client Script

///Reload a Form or Related list from a Client Script

Reload a Form or Related list from a Client Script

T

his post comes in response to a forum question about how to reload a form or related list from a client script. This can come in extremely handy in the right situation. In the past, I’ve used scripts like these to refresh information on the form in response to a back-end server update of some sort. Here are a couple of code examples that show how to trigger these reload actions.


Reload a form

Reloading a form is simple, and it’s already built-in with the ‘Reload form’ context menu action.
Reload Form Action

The client script to reload a form looks like this…

reloadWindow(window);

Refresh a related list

Refreshing a related list is a bit more complex since you need to correctly identify the related list you wish to refresh. You can do that by right-clicking the related list header and selecting ‘Personalize->List Control’. The list control will show you the name of the related list that you need to use. In the screenshot below, the name of the ‘Affected CIs’ related list is ‘task_ci.task’.
List Control

Once you’ve identified the name of the related list, you can refresh it from any client-side script by using the following code (adding your list name where appropriate).

GlideList2.get(g_form.getTableName() + '.YOUR_RELATED_LIST_NAME_HERE').setFilterAndRefresh('');

So if you wanted to set up a client-side ‘Refresh’ UI action for the ‘Affected CIs’ related list, you could do so with the following setup. Notice the use of ‘task_ci.task’ to identify the related list in the ‘Script’ section.

‘Refresh’ related list UI action
Name: Refresh
Table: task_ci
Client: true
List banner button: true
Onclick: refreshAffectedCIs()
Condition: RP.isRelatedList()
Script:

function refreshAffectedCIs(){
   GlideList2.get(g_form.getTableName() + '.task_ci.task').setFilterAndRefresh('');  
}

Refresh an embedded related list

It’s also possible to refresh an embedded related list.

try {
      var elementLookup = $$('div.tabs2_list');
      var listName = "Affected CIs";
      for (i = 0; i != elementLookup.length; i++) {
         if (elementLookup[i].innerHTML.indexOf(listName) != -1) {
            var listHTML = elementLookup[i].id.split('_');
            var listID = listHTML[0];
            nowRefresh(listID);
         }
      }
}
catch (err) {
   //alert(err.message);
}

function nowRefresh(id) {
   GlideList2.get(id).refresh('');
}
By | 2018-07-09T14:59:53-06:00 October 4th, 2012|Categories: Client scripts|Tags: , , |23 Comments

About the Author:

23 Comments

  1. Andreas October 4, 2012 at 1:15 pm - Reply

    Thanks Marc! The solution I was looking for. Works perfectly 🙂
    Keep it up!

  2. R. Hodgins October 8, 2012 at 12:28 pm - Reply

    I recently had to resolve this type of functionality but went a different route. My tables are custom as are the relations so nothing is built in. I needed to have a Related List update with a filter that zeroed in on possible matching records from the source (Related List). The unfortunate part is that I did not have your knowledge of manipulating the List so I triggered off of updating the Form Record.

    The Relationship looks like this:
    Relationship: Your Name Here
    Applied To: Form data source
    Queries From: Foreign Key related Table

    Query With:
    var section=”;
    //gs.log(“** relationship name included: ” + u_icd10pcscodemap.u_section_1.getDisplayValue() );

    if (!u_icd10pcscodemap.u_section_1.nil()) {
    section=u_icd10pcscodemap.u_section_1.getDisplayValue();
    // gs.log(‘query build = ‘+section);
    }

    if (!u_icd10pcscodemap.u_bodysystem_2.nil()) {
    section+=u_icd10pcscodemap.u_bodysystem_2.getDisplayValue();
    }

    if (!u_icd10pcscodemap.u_rootoperation_3.nil()) {
    section+=u_icd10pcscodemap.u_rootoperation_3.getDisplayValue();
    }

    if (!u_icd10pcscodemap.u_bodypart_4.nil()) {
    section+=u_icd10pcscodemap.u_bodypart_4.getDisplayValue();
    }

    if (!u_icd10pcscodemap.u_approach_5.nil()) {
    section+=u_icd10pcscodemap.u_approach_5.getDisplayValue();
    }

    if (!u_icd10pcscodemap.u_device_6.nil()) {
    section+=u_icd10pcscodemap.u_device_6.getDisplayValue();
    }

    current.addQuery(‘u_code’,’STARTSWITH’,section);
    current.query();
    ————–

    I still require a UI Action Button for the Update. I will try your solution instead if I can keep the button generic.

    • Mark Stanger October 8, 2012 at 1:43 pm - Reply

      Cool. Let me know how the other solution works for you.

      • How to autorefresh List Layout December 7, 2012 at 6:55 am - Reply

        I have a situation where our operators always watch the queue example open incidents froma list layout and I want to auto refresh this list for every 2 minutes. We don’t want to use the home page in this situation where the auto refresh option is available.

        • Mark Stanger December 7, 2012 at 7:05 am - Reply

          I don’t have a pre-built solution to refresh a standard list, but I would recommend trying out the module counts functionality I developed. It allows you to see a count of records in the left nav for any module. If you used that, they wouldn’t even have to keep the list up all of the time.

          • Kumar Tella December 7, 2012 at 12:26 pm - Reply

            Thanks Mark. I will try the module count and see how it looks.

  3. Dal May 23, 2013 at 6:25 am - Reply

    Thank you, is it also possible to refresh it in a particular time interval?

  4. Scott November 14, 2013 at 7:32 am - Reply

    Great article! I’m wondering if you know how I would refresh a related list from a client script on itself. I have a related list where someone chooses a quantity on the related list via list edit. Once that list edit is done, I would like to have the related list refresh itself so that the user sees the total cost of that specific item after having calculated qty*unit cost. Thoughts?

    • Mark Stanger November 14, 2013 at 7:51 am - Reply

      You should be able to use an ‘onCellEdit’ client script on the related list table to refresh using the related list refresh code provided above.

      • Scott November 14, 2013 at 8:15 am - Reply

        Thanks, I found my problem… well, atleast one of my problems 🙂

  5. Lindsey April 8, 2014 at 3:22 pm - Reply

    I am somewhat new to SN administration. I am working on a project to build a custom cost accounting application. Most things are going well, however, I’m stuck on my embedded list. While I COULD use a related list, it does not look as nice as the embedded list. With that said, I need the “new” button functionality from the related list on my embedded list.

    I did get the button on the Embedded list form by using the “save with form button” option. This is great, but stealing the script from the normal “new” button does not provide the functionality I am looking for.

    What do I need to do to open the form from the embedded list using the “add time” buttom I’ve created for use with the embedded form? I also need to pass variables (Such as username) to the list on the embedded list. Sounds simple enough, but SN doesn’t always agree with me.

    Any assistance is greatly appreciated!

    • Mark Stanger April 8, 2014 at 5:09 pm - Reply

      Lindsey,

      Thanks for your comment. This is just one of the various issues that you’ll encounter with embedded related lists. Unfortunately, they just don’t work very well for anything other than displaying a static list of content on the form. As a general rule, I avoid them at all costs just because (although they look nice) they are a huge pain to work with. The only suggestion I have is to use a standard related list instead and avoid the use of embedded related lists whenever possible.

      • Lindsey April 9, 2014 at 3:26 pm - Reply

        I have another question, which I know is basic: How do I pass multiple variables to an extended table?

        I have “Cards” for time cards, and I have “Time” to record actual time (Extention of CARD). On the CARD, end users record the reporting period, HR hours recorded (to calculate against) and that is basicially it. The other fields are auto-filled.

        Each Time entry has many more fields, but also need to include the name of the person on the CARD (in case the manager is filling it out) as well as the timeframe. Both of these are lookup fields, and exist on CARD. I have tried everything I can think of, and everything I can find, but I’m not having any luck.

        Could you point me in the right direction? In general, I have not had good luck with passing variables anywhere in SN — I did some workflows a few weeks ago that I FINALLY got to work, but it took a lot of doing.

        Thank you again for your feedback!

        ~Lindsey

        • Mark Stanger April 9, 2014 at 6:34 pm - Reply

          This question is more of a general ServiceNow configuration question so you should probably ask this on the ServiceNow community site.

  6. Steve April 9, 2014 at 5:39 pm - Reply

    Mark,

    Thanks for all the tips you provide, it is very helpful.

    I have a requirement where the Affected Group needs to be embedded to our Change Request form. When the user click on “Request for Approval” UI Action, it will check if there are Affected Groups. If none, it will open a slushbucket (which is also from your site: http://www.servicenowguru.com/system-ui/ui-actions-system-ui/creating-custom-slushbucket-popup-dialog/). I tried to do the code above on refreshing embedded related list, could not get it to work. How does the code for refreshing embedded related list work? Below is the UI Action code. Any help is greatly appreciated.

    function requestApproval() {
        if (g_form.getValue('assigned_to') == '') {
            try {g_form.hideFieldMsg('assigned_to');} catch(e1) {}
            g_form.setMandatory('assigned_to', true);
            g_form.showFieldMsg('assigned_to','Assigned to is required when requesting approval','error');
            return false;  //Abort submission
        }
        var affectedGrp = new GlideRecord('task_group');
        affectedGrp.addQuery('task', g_form.getUniqueValue());
        affectedGrp.query();
        if (!affectedGrp.next()) {
            if (g_form.modified) {
                gsftSubmit(null, g_form.getFormElement(), 'sysverb_update_and_stay');
                gsftSubmit(null, g_form.getFormElement(), 'request.approval'); //MUST call the 'Action name' set in this UI Action
            }
            var dialog = new GlideDialogWindow('affected_groups');
            dialog.setTitle('Affected Group');
            dialog.setPreference('sysparm_groupQuery', 'source=change_request');
            dialog.render();
            try {
                var elementLookup = $$('div.tabs2_list');
                var listName = "Groups affected";
                alert('elementLookup: ' + elementLookup);
                for (i = 0; i < elementLookup.length; i++) {
                    if (elementLookup[i].innerHTML.indexOf(listName) != -1) {
                        var listHTML = elementLookup[i].id.split('_');
                        var listID = listHTML[0];
                        alert('listID: ' + listID);
                        nowRefresh(listID);
                    }
                }
               
                function nowRefresh(id) {
                    GlideList2.get(id).refresh('');
                }
            }
            catch (err) {}
            // gsftSubmit(null, g_form.getFormElement(), 'request.approval'); //MUST call the 'Action name' set in this UI Action
            return false;
        }
       
        //Call the UI Action and skip the 'onclick' function
        gsftSubmit(null, g_form.getFormElement(), 'request.approval'); //MUST call the 'Action name' set in this UI Action
       
    }

    if (typeof window == 'undefined')
        requestForApproval();

    function requestForApproval(){
        current.approval='requested';
        current.state = -5;
        current.update();
        action.setRedirectURL(current);
    }
    • Mark Stanger April 9, 2014 at 6:39 pm - Reply

      There’s a lot more to your script than a simple list refresh. I’ve confirmed that the embedded list refresh works fine in a SN demo environment so I know that’s not the problem here. The only thing I can suggest is to break your script down into more basic sections so you can see where the conflict is. You should probably start with a basic action-invoked refresh and then work up from there.

  7. David December 18, 2015 at 1:56 pm - Reply

    Hello,

    Can you disable/remove status options from a list? Lets say I want to remove the close status from the incident list without using ACLs.

  8. Eric Pace April 27, 2017 at 11:18 am - Reply

    Hey Mark –

    I’m attempting your embedded list script and not having any luck. Does it still require the onclick, client, and condition? I would assume not. I have given my relationship a label and replaced the “Affected CIs” with it, but it still refreshes the entire page, instead of just the embedded list. Ideas?

    • Eric Pace April 27, 2017 at 11:44 am - Reply

      Cancel that. I used the name, not label. I read through the instructions too fast previously. Either way, it’s still not functioning properly for me.

      • Mark Stanger April 27, 2017 at 12:20 pm - Reply

        If it’s a UI action running a client script (as this would need to be) then you need to use the ‘onclick’, and ‘client’ fields. You would also need to wrap the ‘try/catch’ block in a function which would need to be called from the ‘onclick’ field by its function name. You can look at other UI actions in the system that have the ‘Client’ field marked as true to see some examples of how this would be done.

  9. Adam Katulak June 7, 2017 at 3:01 pm - Reply

    Is there anyway that an embedded list can be cleared via a client script or UI action? Basically I would like to hit a UI action on my form that clears all the writable fields, and also does the same behavior as clicking the red x (delete) next to each row in my embedded list.
    Thanks!

    • Mila Morales September 21, 2017 at 1:22 pm - Reply

      There is no possible way to clear the related list by using a UI action on the current form. If you don’t like the related list to be displayed on the form you can remove these lists by configuring the related lists or by creating a button on the related list that will display the records that you need.

Leave A Comment