======Syntax Editor Macros======
==Also located in downloads==
----
====Network Location====
// ADFS with Imprivata MFA should be used to leverage a network location claim
// into SNOW, enabling role based PHI visibility and control.
gs.getSession().getProperty("PHI_access_Role");
----
====doc====
/**
* Description: $0
* Parameters:
* Returns:
*/
----
====for====
for (var i=0; i< myArray.length; i++) {
//myArray[i];
}
----
====info====
gs.addInfoMessage(gs.getMessage("$0"));
----
====vargr====
var gr = new GlideRecord("$tableName");
gr.addQuery("name", "value");
gr.query();
if (gr.next()) {
}
----
====vargror====
var gr = new GlideRecord('$tableName');
var qc = gr.addQuery('field', 'value1');
qc.addOrCondition('field', 'value2');
gr.query();
while (gr.next()) {
}
----
=====Client-Side Key Concepts=====
====JWJ====
//name jwj
//Text
//Client-Side Key Concepts
//default
doc
for
info
vargr
vargror
//Client-Side Key Concepts
c_GeneratingMessages
c_GlideAjaxMethod
c_GlideRecordDatabaseAccess
c_GlideRecordGetReferenceDatabaseAccess
c_ReusableScript
c_ScratchpadDatabaseAccess
c_TryBlock
//Server-Side Key Concepts
s_AjaxFunctionDefinition
s_CurrentAndPreviousGlideRecordObjects
s_EventDefinitionAndTriggering
s_ExcelFileProcessing
s_GeneratingMessages
s_GlideRecordDatabaseAccess
s_GlideRecordDatabaseInsert
s_JavaScriptArrays
s_JavaScriptObjects
s_LibraryClassAndFunctionUsage
s_LibraryClassDefinition
s_LibraryFunctionDefinition
s_MailScript
s_ScratchpadPopulation
s_SetRedirectURLFunction
s_TryBlock
----
====c_GeneratingMessages====
//text
//alert(), addInfoMessage(), showFieldMsg(), jslog(), addDecoration()
//Context: Most client side code.
//Ways to generate messages from client side code:
//Use the alert() function to show a prominent and blocking modal dialog which must be explicitly dismissed for execution to continue.
//Display a message to the user from Client code using g_form.addInfoMessage() or g_form.addErrorMessage()
//Use g_form.addDecoration() to show a small graphic symbol by a form field label. A mouse-over popup hint may be included, and a color may be specified.
//Use g_form.flash() to display a flashing colored background box behind a form field label.
//Use the confirm() function to display a modal popup dialog to get a response (OK or Cancel) from the user before continuing execution.
//Use the jslog() function to write a message to the web browser console.
function onLoad() {
alert("My Alert Message"); //Modal dialog with OK button.
g_form.addErrorMessage("My Error Message"); //Wide message at top of form in Red.
g_form.addInfoMessage("My Info Message"); //Wide message at top of form in Blue.
g_form.showFieldMsg("name", "My Field Message"); //Message UNDERNEATH field. Same width as field. Displayed in blue.
g_form.showFieldMsg("name", "My Field Message - info", "info"); //Again, message UNDERNEATH field. Same width as field. Displayed in blue.
g_form.showFieldMsg("name", "My Field Message - error", "error"); //Message UNDERNEATH field. Same width as field. Displayed in red.
g_form.showFieldMsg("name", "My Field Message - warning", "warning"); //Message UNDERNEATH field. Same width as field. Displayed in orange.
jslog("My jslog Log"); //Sends a message to the web browser console log seen using F12.
g_form.addDecoration("name", "icon-user", "This icon is called icon-user"); //Icon to the left of field.
g_form.addDecoration("name", "icon-tree", "This icon is called icon-tree", "color-green");
g_form.addDecoration("name", "icon-lightbulb", "This icon is called icon-lightbulb", "color-red");
g_form.flash("name", "#AAFACD", -4); //Yellow highlight bar over field for 4 seconds.
var vResult = confirm("My Confirmation Message") ? "User clicked OK" : "User clicked Cancel"; //Modal dialog with 2 buttons.
g_form.addInfoMessage(vResult); //Wide message at top of form in Blue.
}
----
====c_GlideAjaxMethod====
//text
//GlideAjax, addParam(), getXMLAnswer
//From client side code, to invoke server side code asynchronously, instantiate a custom GlideAjax object.
//Use the addParam() function, and by convention, the parameter named "sysparm_name" to specify which server side function to invoke.
//Additional arbitrary parameters may also be specified with addParam(); In this example "sysparm_Prefix".
//Use getXMLAnswer() to invoke the server-side function and specify a callback function; in this example "finishClientSideWorkONE".
//Use a direct parameter in your callback function to make use of data returned by the server; in this case the parameter is named "answerFromServer".
function onLoad() {
g_form.addInfoMessage("BEGIN Client Script");
var ga = new GlideAjax('zJWJ_AjaxFunctions'); //phoenixAjaxUtils is the name of a Server Side Script Include CLASS.
ga.addParam("sysparm_name", "getMyTitle"); //One parameter must be named sysparm_name. It tells which function to invoke on the server.
ga.getXMLAnswer(finishClientSideWork); //Call server function. When it's complete, then invoke "finishClientSideWork" back here on the client.
g_form.addInfoMessage("Additional Code on Client Side 1");
var ga2 = new GlideAjax('zJWJ_AjaxFunctions'); //phoenixAjaxUtils is the name of a Server Side Script Include CLASS.
ga2.addParam("sysparm_name", "getMyTitleWithPrefix"); //Tells which function to invoke on the server.
ga2.addParam("sysparm_Prefix", "Sir "); //Additional custom parameter.
ga2.getXMLAnswer(finishClientSideWorkTWO); //Call server function. When complete, then invoke "finishClientSideWorkTWO" back here on the client.
g_form.addInfoMessage("Additional Code on Client Side 2");
}
function finishClientSideWork(answerFomServer)
{
g_form.addInfoMessage("BEGIN finishClientSideWorkONE");
g_form.addInfoMessage("Title from Server: " + answerFomServer);
g_form.addInfoMessage("END finishClientSideWorkONE");
}
function finishClientSideWorkTWO(answerFomServerTWO)
{
g_form.addInfoMessage("BEGIN finishClientSideWorkTWO");
g_form.addInfoMessage("Title from Server w Prefix: " + answerFomServerTWO);
g_form.addInfoMessage("END finishClientSideWorkTWO");
}
----
====c_GlideRecordDatabaseAccess====
//get(), query(), try(), catch()
//Use Client Side GlideRecord get() method to grab data from the server in a Blocking fashion. And demonstrates UI Policy SCRIPT.
//Use Client Side Glide Record query() method to grab data from the server in an Asynchronous fashion.
//Use JavaScript try{} and catch(){} blocks to ensure continued execution if there is an unhandled exception.
function onCondition() {
//Demonstrate use of CLIENT SIDE GlideRecord object and get() method.
//get() function is synchronous, so the client will be "hung up" until the function call returns from the server.
try{
var myClientSideGlideRecord = new GlideRecord("business_unit");
if (myClientSideGlideRecord.get("acba91b01bdd7c109b1376ae034bcb7e"))
{
g_form.addInfoMessage("Record Name from sys_id: " + myClientSideGlideRecord.name);
}
}
catch (err)
{
g_form.addInfoMessage("err:" + err);
}
//query() function with a parameter is asynchronous, so the client does NOT get hung up. alert 7 is displayed before alert 6.
var rec = new GlideRecord('business_unit');
rec.setLimit(5); //Return no more than 5 records.
rec.query(recResponse);
function recResponse(rec) {
while (rec.next()) {
alert("6: " + rec.name + ' exists');
}
}
alert("7");
}
----
====c_GlideRecordGetReferenceDatabaseAccess====
//Get all the data about a particular reference field from the Server.
g_form.getReference('caller_id', myCallbackFunction); //caller_id is a field on our form. It must be a Reference field.
g_form.addInfoMessage("getReference() call complete.");
function myCallbackFunction(magicalRecordFromServer)
{
g_form.addInfoMessage("Callback function called.");
if (magicalRecordFromServer) //If data returned from server is non-null...
{
g_form.addInfoMessage('magicalRecordFromServer.name:' + magicalRecordFromServer.name);
g_form.addInfoMessage('magicalRecordFromServer.sys_id:' + magicalRecordFromServer.sys_id);
g_form.setValue('short_description', magicalRecordFromServer.name + " " + magicalRecordFromServer.sys_id);
}
}
----
====c_ReusableScript====
//function, addDecoration(), flash()
//Contains client side reusable functions for the Platform UI only. NOT for use in the Portal, Mobile, or Agent Workspace.
//When updating this script, use Web Browser Ctrl + Shift + Del to clear cached files.
//Call attention to a Mandatory field in a standard way.
function oc_ShowMandatoryField(FieldToHighlight, MessageForDisplay)
{
var ocOrange = "#F57F29"; //Orange color from the Optum logo.
var ocMandatoryDecorationColor = "color-red";
var ocMandatoryField_FlashConstant = -4; //-4 indicates seconds.
var ocMandatoryField_DecorationIcon = "icon-alert"; //! icon with a circle around it.
g_form.addErrorMessage(MessageForDisplay);
//g_form.addDecoration(FieldToHighlight, ocMandatoryField_DecorationIcon, MessageForDisplay);
g_form.addDecoration(FieldToHighlight, ocMandatoryField_DecorationIcon, MessageForDisplay, ocMandatoryDecorationColor);
g_form.flash(FieldToHighlight, ocOrange, ocMandatoryField_FlashConstant);
}
----
====c_ScratchpadDatabaseAccess====
//g_scratchpad, g_form.setValue(), g_form.getValue()
//Since client side AJAX code may be slow as it involves asynchronous round trips to the server, a special object called g_scratchpad may be used instead.
//Context: Client Script
//Use the g_scratchpad object from our client side code…
//Retrieve a basic value from a form with g_form.getValue()…
//Set a basic value on a form with g_form.setValue()...
function onLoad() {
g_form.setValue("description", g_form.getValue("description") + " " + g_scratchpad.MyOwnVariable);
}
----
====c_TryBlock====
/* eslint-disable no-console */ //Disables the "Unexpected console statement" warnings.
function RunClientCode(){
try
{
//Write custom code here...
null.MyInvalidFunctionCall();
}
//Catches errors such as the following:
//1) ReferenceError: FunctionXXX is not defined
//2) TypeError: g_form.FunctionXXX is not a function
//3) TypeError: Cannot read properties of null (reading 'MyFunction')
catch (err)
{
var sMessage = "Error caught by catch block: " + err.toString();
g_form.addErrorMessage(sMessage); //alert(sMessage);
console.warn(sMessage);
}
}
----
=====Server-Side Key Concepts=====
====s_AjaxFunctionDefinition====
//AbstractAjaxProcessor, getParameter()
//Declare a class which extends from AbstractAjaxProcessor to define custom server-side functions callable from the Client.
var zGGB_AjaxFunctions = Class.create();
zGGB_AjaxFunctions.prototype = Object.extendsObject(AbstractAjaxProcessor, {
//Server-side function which takes 0 parameters.
getMyTitle: function() {
gs.log("BEGIN zGGB_AjaxFunctions.getMyTitle", "Phoenix");
this.userRec = new GlideRecord('sys_user');
this.userRec.get(gs.getUserID());
return this.userRec.getDisplayValue('title'); //Pass this value back up to the client.
},
//Server-side function which takes 1 implicit parameter.
getMyTitleWithPrefix: function() {
gs.log("BEGIN zGGB_AjaxFunctions.getMyTitleWithPrefix", "Phoenix");
var sysparm_Prefix = this.getParameter('sysparm_Prefix'); //Parameter is retrieved like so. It is not defined explicitly along with the function.
//Use whatever was passed in from the client as our starting point...
var serverResult = "";
if (sysparm_Prefix){
serverResult = sysparm_Prefix;
}
//Then add whatever we can find from the database...
this.userRec2 = new GlideRecord('sys_user');
this.userRec2.get(gs.getUserID());
serverResult += this.userRec2.getDisplayValue('title');
return serverResult; //Pass this value back up to the client.
},
type: 'zGGB_AjaxFunctions'
});
----
====s_CurrentAndPreviousGlideRecordObjects====
//current, previous
//"current" and "previous" are GlideRecord objects defined as parameters in some server-side functions such as Before Update business rules.
//"previous" gives the values of all fields as they were when the record was initially loaded from the database, before any changes were made in the Client UI.
//"current" may be used to change field values before the actual database update happens.
//Context: Business Rule or Workflow
(function executeRule(current, previous /*null when async*/) {
gs.addInfoMessage("previous.description: " + previous.description);
gs.addInfoMessage("current.description: " + current.description);
var sNewDescription = current.description + "X";
gs.addInfoMessage("sNewDescription: " + sNewDescription);
current.description = sNewDescription;
})(current, previous);
----
====s_EventDefinitionAndTriggering====
gs.eventQueue(
"incident.notifycustomer", //Event Type to send
current, //Glide Record object paremeter
gs.getUserName(), //Event Parameter 1
gs.getUserID() //Event Parameter 2
);
gs.addInfoMessage("Event Sent!");
action.setRedirectURL(current);
----
====s_ExcelFileProcessing====
//GlideExcelParser, GlideSysAttachment, getContentStream(), parse(), getRow()
//Shows how to parse an Excel file so that you can take some action for each record in the given file.
//https://developer.servicenow.com/dev.do#!/reference/api/quebec/server/GEPS-getRow
//Step 0. Strip unnecessary content and formatting form the Excel file so it contains only the data you need and file size is very small < 5 MB.
//Step 1. Attach the Excel File to any record in the system.
//Step 2. Hover over the attachment link, Right Click, and use the Copy Link Address command...
//Step 3. Paste the link address into Notepad to get the sys_id, for example: d97591e58724015089ebc88e8bbb3532
//Step 4. Use that sys_id in the getContentStream() functino call, below.
var parser = new sn_impex.GlideExcelParser();
var attachment = new GlideSysAttachment();
var attachmentStream = attachment.getContentStream("d97591e58724015089ebc88e8bbb3532"); //sys_id of Excel file attached to any ServiceNow record.
parser.parse(attachmentStream);
//Retrieve the column headers
var headers = parser.getColumnHeaders();
var header0 = headers[0];
//Display headers
//gs.addInfoMessage("Excel Header 0: " + header0);
while(parser.next()) {
var row = parser.getRow();
var incidentGr = new GlideRecord("incident");
if (incidentGr.get("number", row[header0])){
gs.addInfoMessage("Major Incident " + row[header0] + " Old Review Status Value: " + incidentGr.getValue("u_review_status"));
incidentGr.setValue("u_review_status", "Complete");
gs.addInfoMessage("Major Incident " + row[header0] + " New Review Status Value: " + incidentGr.getValue("u_review_status"));
incidentGr.update();
}
else
{
gs.addInfoMessage("Major Incident " + row[header0] + " NOT FOUND!");
}
}
parser.close();
----
====s_GeneratingMessages====
//addInfoMessage(), gs.log
//Push messages from the server up to the client form using gs.addInfoMessage() or gs.addErrorMessage().
//Write to table "syslog" with gs.info(), gs.warn(), or gs.error().
//Write to table "syslog" but with a custom Data Source using gs.log(), gs.logWarning, or gs.LogError(); here the custom data source is "Phoenix".
//Use the "Debug Now" custom UI Action to execute this script synchronously in your current user session..
//The "Execute Now" button will run this script asynchronously, in a different session, so you will not see form messages, for example.
gs.addErrorMessage("My Error Message From Server"); //Server-Side code that pushes a message back up to the client: Wide message at top of form in Red.
gs.addInfoMessage("My Info Message From Server"); //Server-Side code that pushes a message back up to the client: Wide message at top of form in Blue.
//SERVER SIDE DEBUGGING
gs.log("My log message"); //Log message to table: syslog.
gs.info("My info message"); //Equivalent to gs.log.
gs.error("My error message");
gs.warn("My warning message");
gs.log("My Phoenix informational message", "Phoenix"); //Log message to table "syslog", Source "Phoenix".
//Shown below form on client, if "System Diagnostics - Session Debug" is turned ON for the "log" object type.
gs.debug("My gs.debug message"); //Also shown in the separate Session Log window.
----
====s_GlideRecordDatabaseAccess====
//GlideRecord, addQuery(), orderBy(), setLimit(), getValue(), query(), next(), while(), get()
gs.addInfoMessage("START");
var recLimit = 5;
//List the numbers of the first 5 incident records.
var myGR= new GlideRecord("incident"); //Table names are case sensitive.
myGR.addQuery("active", true); //Only active records.
myGR.orderByDesc("number"); //Sort by number.
myGR.setLimit(recLimit); //Return only 5 records.
myGR.query();
gs.addInfoMessage("Row Count: " + myGR.getRowCount());
var recsFound = myGR.hasNext();
if (recsFound) gs.addInfoMessage("Start Listing of first " + recLimit + " incident records.");
while (myGR.next())
{
gs.addInfoMessage(myGR.getValue("number"));
//gs.addInfoMessage(myGR.number); //This works also. Alternate syntax.
}
if (recsFound) gs.addInfoMessage("Completed the Listing of the first " + recLimit + " incident records.");
//Get a single record by its sys_id.
var quickGR = new GlideRecord("incident");
if (quickGR.get("sys_id", "9d385017c611228701d22104cc95c371")){
gs.addInfoMessage(quickGR.getValue("number"));
gs.addInfoMessage(quickGR.getValue("sys_id"));
}
gs.addInfoMessage("END");
----
====s_GlideRecordDatabaseInsert====
//initialize, insert
//Use the GlideRecord initialize() function to obtain a new record number.
//Use the GlideRecord insert() function to save the new record to the database.
var grNew= new GlideRecord("rm_story");
grNew.initialize(); //INITIALIZE
grNew.short_description = current.short_description;
grNew.description = sDescription;
grNew.acceptance_criteria = "TBD";
grNew.state = 2;
grNew.product = "cc341ebfdb989490dd5ff27139961948"; //"ServiceNow Production"
grNew.assignment_group = "9ebc734a78dcc500ba880a8925f7fefd"; //"ServiceNow Admin"
grNew.u_customer_lead = current.requested_for;
grNew.parent = current.sys_id;
grNew.insert();
gs.addInfoMessage("New Story Number: " + grNew.number);
----
====s_JavaScriptArrays====
//https://www.w3schools.com/js/js_arrays.asp
//You should use objects when you want the element names to be strings (text).
//You should use arrays when you want the element names to be numbers.
var cars = ["Saab", "Volvo", "BMW"]; //Define an array with square bracket notation.
gs.addInfoMessage("cars: " + cars); //Shows all elements of the array.
gs.addInfoMessage("cars.length: " + cars.length);
cars[0] = "Ford"; //Access array elements with square bracket notation.
gs.addInfoMessage("cars[0]: " + cars[0]); //Shows just one element of the array. The first element is at offest 0 of course.
cars.sort();
gs.addInfoMessage("Sorted Car Array: ");
//Regular for loop.
for (var i = 0; i < cars.length; i++) {
gs.addInfoMessage("cars[" + i + "]: " + cars[i]);
}
cars.pop(); //Removes the last element.
cars.push("Nissan"); //Adds an element to the end of the array.
//forEach loop, which calls a function and passes in each value automatically.
cars.forEach(myFunction);
function myFunction(value) {
gs.addInfoMessage("myFunction(). value: " + value);
}
----
====s_JavaScriptObjects====
//https://www.w3schools.com/js/js_objects.asp
//An object is a built-in data type for storing properties (key-value pairs). Data inside objects are unordered, and the values can be of any type.
var apple = { //Define using curly brackets { }
color: "Green", //Use colons : between the key and the value of each property.
family: "Fruit",
price: "$3/kg",
method1 : function(arg1, arg2) { //Methods are declared by putting the method identifier BEFORE the keyword function, unlike usual.
return arg1 + arg2 + this.color; //Inside an object method, the keyword this refers to the object itself.
}
};
gs.addInfoMessage(JSON.stringify(apple)); //This will show: {"color":"Green","family":"Fruit","price":"$3/kg"} //Note: Methods are Not listed.
gs.addInfoMessage("apple.color: " + apple.color); //Use Dot notation to reference values.
gs.addInfoMessage('apple["color"]: ' + apple["color"]); //Use Bracket notation to reference values via a key name string. Note the quotes.
if (apple.bogusProperty) gs.addInfoMessage(apple.bogusKey); //An if statement can be used to test for: undefined
gs.addInfoMessage("Listing properties of apple object via for loop:");
for (var appleKey in apple) { gs.addInfoMessage(appleKey + " : " + apple[appleKey]); }
gs.addInfoMessage( apple.method1(5,10) ); //Example of calling a method of the object.
//Creating an object from a string.
var sObject = '{"size":"Large", "color":"Red", "age":"Old"}';
var myObject = JSON.parse( sObject );
gs.addInfoMessage("Listing properties of myObject via for loop:");
for (var myObjectKey in myObject) {
gs.addInfoMessage(myObjectKey + " : " + myObject[myObjectKey]);
}
----
====s_LibraryClassAndFunctionUsage====
//new
//To call a script include library method from other server-side code, instantiate the class using the new keyword, then call named functions as usual.
//To call a script include Classless library function from other server-side code, simply invoke the function name directly.
//Example of instantiating a script include helper class.
var vUtilityFunctions = new PhoenixUtilityFunctions();
//Simple function call on script include helper class.
var vEmail = vUtilityFunctions.getMyEmail();
gs.addInfoMessage("Email from Script Include Utility Function: " + vEmail);
//Simple function call on script include helper class, omitting optional parameter.
var vMyName2 = vUtilityFunctions.getMyNameTwoWays();
gs.addInfoMessage("Name from Script Include Utility Function: " + vMyName2);
//Simple function call on script include helper class, passing in a parameter.
var vMyName = vUtilityFunctions.getMyNameTwoWays(false);
gs.addInfoMessage("Name from Script Include Utility Function: " + vMyName);
var city = zGGB__ClasslessFunction();
gs.addInfoMessage("City from Script Include Classless Function: " + city);
----
====s_LibraryClassDefinition====
//prototype, Class.create(), this, function()
//Use the .prototype keyword and the Class.create() method to declare a regular library class containing various (non-AJAX) utility functions.
//Use the this keyword to declare and utilize instance variables.
var PhoenixUtilityFunctions = Class.create();
PhoenixUtilityFunctions.prototype = {
initialize: function() {
},
//Simple object-based function (method).
getMyEmail: function(){
this.userRec = new GlideRecord('sys_user');
this.userRec.get(gs.getUserID());
return this.userRec.getDisplayValue('email');
},
//Simple method which accepts one parameter.
getMyNameTwoWays: function(bFirstLast){
if (bFirstLast === undefined) {bFirstLast = true;}
var vUserId = gs.getUserID();
this.userRec = new GlideRecord('sys_user');
this.userRec.get(vUserId);
var vLastName = this.userRec.getDisplayValue("last_name");
var vFirstName = this.userRec.getDisplayValue("first_name");
var vCompleteName = vFirstName + " " + vLastName;
if (! bFirstLast)
{
vCompleteName = vLastName + ", " + vFirstName;
}
return vCompleteName;
},
type: 'PhoenixUtilityFunctions'
};
----
====s_LibraryFunctionDefinition====
//function
//Context: Script Include
//Example of defining a "Classless" script include function. These may only be called from server side code, NEVER client side code.
//One downside of this method is that it requies a separate script include record for each function.
function PhoenixClasslessFunction()
{
var userSysId = gs.getUserID();
var userRec = new GlideRecord('sys_user');
userRec.get(userSysId);
if (userRec) return userRec.getDisplayValue('city');
}
----
====s_MailScript====
//runMailScript, url, uri, template.print()
//Generate an instance-specific Hyperlink to the Service Portal "My Approvals" page.
(function runMailScript(current, template, email, email_action, event) {
var sAnchorTag = 'Portal Approvals';
sAnchorTag = sAnchorTag.replace("[XXX]", gs.getProperty('glide.servlet.uri'));
template.print(sAnchorTag);
})(current, template, email, email_action, event);
----
====s_Object====
//object, property definition, function definition, stringify(), dot Notation, bracket notation with quotes, testing for properties, for loop with in operator, method calls, JSON.parse(),
//https://www.w3schools.com/js/js_objects.asp
//An object is a built-in data type for storing properties (key-value pairs).
//Data inside an object is unordered, and the values can be of any type.
var apple ={
color: "Green",
family: "Fruit",
price: "$3/kg",
method1: function(arg1, arg2){
return arg1 + arg2 + this.color;
}
};
gs.addInfoMessage(JSON.stringify(apple)); //This will show: {"color":"Green,"family":"Fruit","price:"$3/kg"} Note that methods are not listed.
gs.addInfoMessage("apple:color: " + apple.color); //Use dot notation to reference individual values.
gs.addInfoMessage('apple["color]": ' + apple["color"]); //You may also use bracket notation and key names within quotes
if (apple.bogusKey)
gs.addInfoMessage(apple.bogusKey); //An if statement can be ued to test for undefined properties.
gs.addInfoMessage("Listing properties of apple via for loop, including methods:");
for (var appleKey in apple){
gs.addInfoMessage(appleKey + " : " + apple[appleKey]);
}
gs.addInfoMessage("Method call result:");
gs.addInfoMessage( apple.method1(5, 10)); //Example method call.
//Creating an object from a string.
var sObject = '{ "size":"Large", "color":"Red", "age":"Old" }';
var myObject = JSON.parse(sObject);
gs.addInfoMessage("Listing properties of myObject via for loop:");
for (var myObjectKey in myObject){
gs.addInfoMessage(myObjectKey + " : " + myObject[myObjectKey]);
}
----
====s_ScratchpadPopulation====
//g_scratchpad
//Since client side AJAX code may be slow as it involves asynchronous round trips to the server, a special object called g_scratchpad may be used instead.
//Any "display" type business rule may proactively fill the g_scratchpad object with data which will be available for use on the client.
//Context: Business Rule of type "Display".
//Populate the scratchpad from server side code…
(function executeRule(current, previous /*null when async*/) {
g_scratchpad.MyOwnVariable = "XYZ";
})(current, previous);
----
====s_SetRedirectURLFunction====
//setRedirectURL(), Debug Now
//This custom UI Action, "Debug Now" executs "Scheduled Script Execution" scripts (from table "sysauto_script") in the current session.
//Execution in the current session allows the script debugger (and breakpoints) to be used, and lets you see client side messages such as infoMessages.
try{
var evaluator = new GlideScopedEvaluator();
evaluator.evaluateScript(current, 'script');
action.setRedirectURL(current);
}
catch(e){
gs.addInfoMessage(e);
}
----
====s_TryBlock====
//Single LIne Try Catch Block. Catches errors such as use of undefined functions or methods, or attempting to reference fields of a null object.
try { RunServerSideCustomCode(); } catch(err){ var s = "Error caught by catch block: " + err.toString(); gs.error(s); gs.addErrorMessage(s); }
function RunServerSideCustomCode(){
//Write custom code here...
null.MyInvalidFunctionCall();
}
----
----