Announcing the Global SNUG Board of Directors. Learn more here

Help
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 
Chuck Tomasi
ServiceNow Employee
ServiceNow Employee

find_real_file.pngFor 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.

find_real_file.png

Let's use the following scripts to illustrate the emergency change/alert example above.

Name: hasAttachments
Table: Change Request [change_request]
Order: 100
Active: true
When: display
Condition: (empty)
Script:



// Check for attachments and save it in the g_scratchpad
g_scratchpad.hasAttachments = current.hasAttachments();

Now we can create an onLoad client script:

Name: Change Attachment Alert
Active: true
Global: true
Type: onLoad
Table: Change Request [change_request]
Inherited: false
Script:



function onLoad() {
  if (g_form.getValue('type') == 'Emergency' && g_form.getValue('state') == '2' && !g_scratchpad.hasAttachments) {
      alert("Don't forget your attachments");
  }
}

Hopefully you'll find good uses for the g_scratchpad and start communicating more effectively between your server and client scripts.

Reference:

Differences Among Scripts - ServiceNow Wiki

Business Rules - ServiceNow Wiki

Business Rules Best Practices - ServiceNow Wiki  

15 Comments