Tip: Server Side Functions and Client Scripts
For years I've been told by my colleagues to use server side scripts in ServiceNow when ever possible to keep from slowing down things like form loads. However, there are times when I need some server side information on the client and for some reason (probably conditioning) cringe at the thought of retrieving it from an Ajax call. By using the g_scratchpad object, I'll show you how to leverage server side script functions to "set up" information that the client script can consume.
This is just one of several tips I have coming up to help make you more effective at script writing, because bad scripting habits can lead a poor user experience.
Here's an example based on a recent customer requirement; present an alert message when an emergency change request is in the state "Plan", and has no attachment yet.
Wouldn't it be nice if there was a client side function to detect if there are attachments on a record? I thought so to, but there isn't. Fortunately, there's an easy way to do this. From the server side, we can use
current.hasAttachments()
to get a boolean value (true=this record has attachments, false=no attachments found.) Using the g_scratchpad object, we can store that value and pick it up with a client script. This is a great place to use a display business rule to do the set up.
Display business rules are the server side analog of an onLoad client script. When a record is requested, the display business rule runs, then the form is presented. The cool part is that the display business rules run before the onLoad client scripts, so it becomes quite easy to put something in the g_scratchpad with a display business rule and pick it up with an onLoad client script.
Let's use the following scripts to illustrate the emergency change/alert example above.
Name: hasAttachmentsTable: Change Request [change_request]Order: 100Active: trueWhen: displayCondition: (empty)
Script:
https://www.servicenow.com/community/in-other-news/tip-server-side-functions-and-client-scripts/ba-p/2276039