Script examples

The advanced server-side techniques we have seen can be used in a number of ways, and you will find advanced server-side scripting to be some of the most common in the ServiceNow platform.

Now that we have seen where to write our advanced server-side code, we can have a look at some further examples to solidify our understanding.

Let's have a look at a script include example first. We will write a script to return the active tasks of a requested item. This can be helpful for letting users know which tasks need to be completed for an item to be fulfilled.

First we will take a look at the script include code:

var item_utils = Class.create();
item_utils.prototype = {
initialize: function() {
},

getActiveTasks: function getActiveTasks(item) {

var tasks = [];
var task = new GlideRecord('sc_task');
task.addQuery('request_item', item.sys_id);
task.addActiveQuery();
task.query();
while (task.next()) {
tasks.push(task.number.toString());
}
return tasks;
},

type: 'item_utils'
};

We are using the getActiveTasks method to get all of the active tasks returned to us, passing in the item parameter as the requested item record to get the tasks for. Using a gliderecord query, we can find all of the tasks, and are returning them as an array.

In the example, we have started the creation of an item utilities script include. You will often find these in ServiceNow instances having been developed by other developers. We have created the first method here, but you would usually build up more methods for requested items as part of this class to keep the code organized.

We can see what the script include will look like in Figure 6.6:

Figure 6.6: Item utilities script include

Now that we have the script include, we need to call it from another location. Here, we will do this from a business rule, and simply log the result. You can use this type of script include to assist in whether to close out requested items, too.

Here is the code for the business rule to call the script include:

(function executeRule(current, previous /*null when async*/) {

var tasks = new item_utils().getActiveTasks(current);
gs.log('Active tasks for ' + current.number + ' are ' + tasks.toString());

})(current, previous);

We would run this business rule on the requested item table. In the code block, we put the value of the script include into the tasks variable. We also pass the current requested item record using current. We are just logging the output here, but this data could be used for other uses.

Let us also see what the business rule would look like, in Figure 6.7:

Figure 6.7: Business rule to log active requested item tasks

Now, let us have a look at a further example of a scheduled job.

For this example, we will look at deleting all incidents that are over a year old. This kind of example shows how we can remove old records overnight for different tables.

Let us have a look at what the code would look like:

//Delete incidents that have not been updated in the last year.
var date = new GlideDateTime();
date.addYearsLocalTime(-1);

var delIncident = new GlideRecord('incident');
delIncident.addQuery('sys_updated_on', '<', date);
delIncident.deleteMultiple();

In this code, we get the current date and time by initiating a new GlideDateTime class, and then removing a year from this time. By using a negative number, in this case -1, we subtract a year from the current date and time. Using a GlideRecord query, we are finding all of the incidents updated over a year ago, and deleting them using deleteMultiple. This deletes all of the records without the need to query the Gliderecord.

This type of overnight job can be great for clearing out old records or performing updates, ready for the day ahead.

Figure 6.8 shows what the scheduled job itself looks like:

Figure 6.8: Scheduled job to delete old incidents

As you can see in the preceding figure, this scheduled job would run at 1:00 a.m. and delete the incidents overnight. This is common practice so that system resources are not being used during the working day.

It is also best practice to run long-running scripts overnight so that they do not impact the instance resources during business hours. There are also jobs that run overnight written by ServiceNow included in a brand new instance; for example, the import set deleter, which cleans up import sets after seven days.

Running overnight scripts is a great way to use scheduled jobs. This can be useful for cleaning up old data or setting up reports so that they are available to users first thing in the morning.

Now, let us have a look at a workflow script example.

Here, we will use an approval activity to add an approval that is the director in charge of the current caller. This involves iterating through managers of users in the database until we find one that is a director.

Let us take a look at the code:

var manager = 'current.caller_id.manager';
var title;
while (eval(manager) != '') {
title = manager + '.title';
if (eval(title) == 'Director') {
ans = manager + '.sys_id';
answer = eval(ans);
break;
}
manager = manager + '.manager';
}

In the example, we use the manager string to keep adding .manager to until we find a user that is a director. This means saying the manager of the manager of the manager, and so on, until a director is found. We can execute this in a loop to save time and resources by using eval

eval evaluates the contents of the brackets, rather than treating it as its current type: in this case, a string. This allows us to dot walk to find the title of the user and get the sys_id if we find a director. It is also how we can use a loop here, adding .manager to the string each time we run through the loop. eval can be very helpful when using script to find the field you require, and then to evaluate it once it is found.

If no director is found, then no approval will be added at this stage in the workflow, as when we get to the top of the organisational tree we would meet a user with no manager and exit the loop.

We can see the approval activity from the workflow in Figure 6.9:

Figure 6.9: Approval activity to find and add the user's director as an approver

For our final example, we will take a look at a script action.

Sometimes we want to put an incident on hold, but incidents can get left on hold for extended periods of time. In this example, we will create a new field to hold a date and time for the incident to stay on hold until. Once the date and time are reached, an event fires which will run our script action and take the incident off hold and move the state to in progress.

To achieve this goal, we also need to set the event to be scheduled in the future. Here, we will use a business rule to do this. The code we will need looks as follows:

(function executeRule(current, previous /*null when async*/) {

gs.eventQueueScheduled("incident.off.hold", current, current.sys_id, gs.getUserName(), current.u_on_hold_until);


})(current, previous);

In the business rule, we are using the GlideSystem method eventQueueScheduled to put an event into the system scheduler. We have set the third parameter, or what can be referenced as event.parm1, in later scripts to be the sys_id of the current incident. You will also notice that the final fifth parameter is the value of our custom field to hold the date and time we want the incident to stay on hold until.

This method sets an event into the system scheduler which will run the event at the time we have set in the custom on hold until field. The event we are firing (incident.off.hold) is a custom one we have created for this particular functionality.

Once the event fires, we need to move the incident out of the on hold state and into in progress. For this, we are going to use our script action.

The code in our script action is as follows:

var incident = new GlideRecord('incident');
incident.get(event.parm1);
incident.state = '2';
incident.u_on_hold_until = '';
incident.update();

We are using the event parameter we set in the business rule to use gliderecord to get the incident record we want to update. Once we have the record, we can change the state to in progress, with a value of two, and reset the on hold until field before updating the incident record.

We can also see the full script action in Figure 6.10:

Figure 6.10: Script action to take an incident off hold

This combination of business rule and script action is a very useful technique to know for having the ability to run scripts at a specified time in the future.

These practical examples are great for reinforcing the understanding of these more advanced server-side script techniques.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.152.162