Servicenow 简明教程

ServiceNow - Development

ServiceNow 提供了许多内置功能和应用程序,我们可以轻松使用它们在任何组织中实施 ITSM。同时,存在设置不同流程和特性的业务需求。ServiceNow 具有高度可定制性,开发人员可以使用 Javascript 原则轻松地根据客户需求创建应用程序和模块。

ServiceNow provides a lot of inbuilt features and applications, which we can easily use to implement ITSM in any organisation. At the same time, there are business requirements to set up different processes and features. ServiceNow is highly customisable and developers can easily create applications and modules based on customer’s requirements using principles of Javascript.

Javascript 是 ServiceNow 脚本的必需品。在本部分中,我们将概述 ServiceNow 开发。

Javascript is mandatory for ServiceNow scripting. In this section, we will give you an overview of ServiceNow development.

Application Creation Overview

ServiceNow 提供了一个名为“工作室”的应用程序,您可以在其中创建新的应用程序、提供源代码、为您的应用程序创建新表等。该工作室为创建新应用程序提供了指导性和易于使用的界面。让我们为 BookWorm ltd. 的以下案例创建一个新应用程序。

ServiceNow provides an application called “Studio”, where you can create your new applications, give the source codes, create new tables for your applications, etc. The Studio provides guided and easy to use interface for creating new applications. Let’s create a new application for the following case of BookWorm ltd.

前端 IT 团队需要一个 ServiceNow 应用程序,经理可以在其中发布轮班 ROTA(轮班轮换)。每个员工将有 6 小时的轮班,团队必须 24 X 7 全天候提供支持。

The Frontend IT team needs an application in ServiceNow wherein the Manager can publish the shift ROTA (shift rotation). There would be a 6 hrs shift for each employee and the team has to support 24 X 7.

从导航器进入工作室,将打开一个新窗口。点击创建应用程序。系统将提示您输入应用程序名称和描述。最后,点击创建。

From the navigator goto Studio, a new window will open. Click on Create application. You will be prompted to enter the application name and description. Finally, click Create.

application creation overview

您将在下面找到应用程序页面。现在,是为我们的应用程序创建表的时候了。转到“创建应用程序文件”。

You will find the application page below. Now, it is time to create a table for our application. Go to “Create application file”.

create application file

在数据模型下点击表并点击创建。系统将提示您输入新表的详细信息。给出表名并将其他详细信息保留为默认值。

Click on Table under Data model and click create. You will be prompted to enter the details for the new table. Give the name of the table and keep remaining details as default.

table new record

现在向下滚动并开始定义这些表的列。我们有以下列定义,这里要注意的重要一点是,我们已经在成员列中选择了 sys_user 的引用。

Now scroll down and start defining the columns for these tables. We have below column definition, the important point to note here is that, we have selected reference of sys_user in Member column.

table columns

现在,点击轮班列并选择“创建选项列表”,因为在这里,我们将创建 6am-12pm、12pm-6pm、6pm-12am 和 12am-6am 等轮班选项。

Now, click on the Shift column and select “Create choice list” as here, we will create choices of shift like 6am-12pm, 12pm-6pm, 6pm-12am and 12am-6am.

create choice list

因此,现在我们已经创建了表,在工作室中的应用程序看起来是这样。

So, now that we have created the table our application in the studio looks like this.

application explorer

工作室已经为我们自动创建了表单、列表、模块、应用程序菜单。我们可以从创建应用程序文件选项创建其他模块、表、UI 等,就像我们为创建 ROTA 表所做的那样。

The studio has automatically created Form, list, module, application menu for us. We can create additional modules, tables, UI etc. from the create application file option, as we did for creating the ROTA table.

现在让我们看看我们的应用程序在现有的服务中是什么样子。在导航栏中搜索 Frontend_IT_ROTA,并进入我们的新模块。

Now let’s see how our application looks in service now. Search Frontend_IT_ROTA in the navigation bar and go to our new module.

让我们继续在应用程序中添加一些新的 ROTA 记录。单击新建按钮。

Let’s go ahead and add some new ROTA records in our application. Click on the New button.

service management
service management1
service management2

UI Policy and Actions

ServiceNow 将 UI 策略定义为一种工具,我们通过该工具可以动态更改表单中信息的处理方式,并控制任务的自定义流程。另一方面,UI 操作用于使 UI 更具交互性、更个性化且更贴合用户活动。让我们借助一个示例来理解这一点。

ServiceNow defines UI policies as a tool through which, we can dynamically change the behaviour of information on a form and control custom process flows for tasks. UI action on the other hand is used to make the UI more interactive, customised, and specific to user activities. Let’s understand this with the help of an example.

假设,我们必须配置事件表单,使其在任何事件被分配到前端 IT 团队分配组时,服务字段将变为不可见,配置项应被禁用。此处的 UI 策略是:“如果分配组选为前端 IT 团队”,此处的 UI 操作是:“服务字段将变为不可见,配置项字段应被禁用”。

Suppose, we have to configure the Incident form in such a way that, if any incident is assigned to the Frontend IT team assignment group then, the Services field should become invisible and Configuration items should get disabled. The UI policy here is, “if assignment group is selected as frontend IT team” and UI actions here, is “Services field should become invisible and Configuration item field should get disabled”.

UI 操作可以通过一种简单的方法来实现,使用界面,也可以通过客户端脚本来实现。编写客户端脚本将帮助我们对字段执行高级操作。我们还将在本节后面展示客户端脚本。

The UI action can be implemented through, an easy way to use interface and also through the client script. Writing client script will help us, to do advanced operations in the fields. We will also demonstrate the client scripting later in this section.

这里需要注意的重要一点是,UI 操作更快并且会先执行,然后是客户端脚本。让我们针对我们的用例创建一个 UI 策略和操作。在导航栏中,在“系统 UI”应用程序下打开“UI 策略”模块,然后单击“新建”按钮。

The important point to note over here is that, UI actions are faster and executed first, followed by client scripts. Let’s create an UI policy and action for our use case. From the navigation bar, open “UI policy” module under “System UI” application and click on New button.

system ui

填写表的名称,在我们这里为 Incident。将应用程序保留为 Global。如果您找不到全局选项,请导航到右上角的齿轮,然后在开发人员选项卡中将应用程序选择为全局。

Give the name of the table, it is Incident in our case. Keep application as Global. If you can’t find the option of global, navigate to the cog wheel in the top right corner and from developer tab select application as global.

现在,开始在下一节中给出条件。在我们的示例中为“分配组是前端 IT 团队”。接下来,这里有几个复选框,如下所示:

Now, start giving the conditions in the next section. It would be “Assignment group is Frontend IT team” in our case. Next, there are some checkboxes, which are as follows −

  1. Global − tick if you want, your UI policies to be implemented globally.

  2. On load − tick if you want, to run your UI policy every time the page is refreshed.

  3. Reverse if false − tick if you want, to reverse all the actions which we created if the conditions are changed.

  4. Inherit − tick if you want, the table (in which UI policy is created) that extend the specified table inherit this UI Policy.

填写所有必需的详细信息并按提交。

Fill all the required details and press submit.

ui policy record

现在,再次打开 UI 策略,您将找到输入 UI 操作的选项。让我们根据我们的用例提供 UI 操作。单击 UI 操作部分中的“新建”按钮。

Now, open the UI policy again and you will find the option to enter the UI actions. Let’s give the UI actions as per our use case. Click on the New button in the UI action section.

ui policy action

我们将选择服务和配置项字段的以下操作。

We will select the following actions for Services and Configuration items fields.

services and configuration items fields
services and configuration items fields1

单击提交以确认您的 UI 操作,最后,单击“更新”以保存 UI 策略中的更改。您现在可以转到事件表单并验证您的 UI 策略和操作。

Click submit to confirm your UI actions and finally, click ‘Update’ to save the changes in UI policy. You can now go, to incident forms and verify your UI policy and actions.

ServiceNow Scripting

ServiceNow 中有两种类型的脚本,即客户端和服务器端。服务器端脚本表示处理发生在 Web 服务器上,而客户端脚本表示处理发生在用户计算机上。有特定的任务可以通过每种类型的脚本来完成。让我们讨论一下这两个脚本的示例:

There are two types of scripting in ServiceNow, which are Client side and Server side. The server side scripting means that, processing takes place at the web server, while client scripting means, processing takes place at the user’s machine. There are specific tasks, which could be accomplished by each type of script. Let’s discuss, examples of both the scripts −

Client side scripting

客户端脚本可用于各种场景,例如填充表单字段中的某些默认值、显示某些警报消息、根据表单中另一个字段中的用户响应在某个字段中设置值、更改选项列表等。一共有三种主要类型的客户端脚本。

The client side scripting can be used in various scenarios like populating some default values in the field of form, displaying some alert message, setting value in one field based on the response by the user in another field in a form, altering the choice list, etc. There are three main types of client scripts.

  1. Onload() - This gets executed, when the form is loaded.

  2. Onchange() - This gets executed, when particular field in the form is changed.

  3. Onsubmit() - This gets executed, when form is submitted.

让我们为两个用例创建客户端脚本。在我们新的应用程序“Frontend IT team ROTA”中,应用程序加载后我们将实现一条警报“请每周使用此应用程序一次,以设置班次轮换”。然后,如果班次时间选择为 12am-6am,我们将显示一条警报“该成员有资格获得轮班补贴”。

Let’s create a client script for two use cases. In our new application, “Frontend IT team ROTA”, we will implement an alert “Please use this application once a week, to set shift rotation”, once the application is loaded. Then, we will display an alert “The Member is entitled for shift allowance”, if the shift timing is selected as 12am-6am.

导航至 Studio 模块,打开应用程序并单击“创建应用程序”文件。然后,选择客户端开发选项下的客户端脚本,并提供如下所需详细信息:

Navigate to Studio module, open the application and click ‘Create application’ file. Then, select client script under client development option and give the required details as below −

create application

向下滚动并提供脚本。我们将在下方提供一条警告。

Scroll down and give the script. We will give an alert as below.

create application1
Function onLoad() {
alert (“Please use this application once a week to set the shift rotation”);
}

单击提交并加载您的新应用程序以查看结果。

Click submit and load your new application to see the result.

现在,让我们实现下一个用例。在此,我们将使用 onChange。onChange 函数自动由 ServiceNow 传递 5 个参数。

Now, let us implement the next use case. Here, we will use onChange. The onChange Function is automatically passed with 5 arguments by ServiceNow.

  1. Control − It is the field for which the Client Script is configured

  2. OldValue − It is the value of the field, when the form is loaded (prior to the change).

  3. newValue − It is the value of the field after the change.

  4. isLoading − It is the boolean value indicating whether, the change is occurring as part of a form load. Value is true if, change is due to a form load. When form loads, all the field values on the form changes.

  5. isTemplate − It is the boolean value indicating whether, the change that occurred, is due to the population of the field by a template. Value is true if, change is due to population by a template.

client script
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
   if (isLoading || newValue === '12am-6pm') {
      alert("The member is entitled for shift allowance");
      return;
   }
}
client script1

Glideform (g_form) class

glideform 是用于控制表单及其字段的类。我们可以执行任务,例如隐藏字段的值,根据其他字段的响应设置字段的值,将字段添加到选项列表中等。

The glideform is the class which is used to control the forms and the fields of the forms. We can perform tasks such as Hide a value of field, set the value of field based on the response on the other fields, add fields to choice list, etc.

glide form 类附带许多方法。一些重要的方法是 addOption()、clearOptions()、showFieldMsg()、clearMessages()、clearValue()、setValue() 等。

The glide form class comes with many methods. A few important methods are addOption(), clearOptions(), showFieldMsg(), clearMessages(), clearValue(), setValue(), etc.

让我们在事件表单中创建一个客户端脚本,以便在将分配组选择为 Frontend IT team 的情况下填充说明字段中的一些信息。转到 UI 策略并创建新策略。在“应用到何处”部分中给出条件为“分配组是 Frontend IT 团队”。

Let’s create a client script in incident form to populate some message in the description field, if the assignment group is selected as the Frontend IT team. Go to UI policies and create a new policy. Give the condition in the “Where to apply” section as “Assignment group is Frontend IT team”.

ui policy advanced view

提交 UI 策略,再次打开它,然后单击高级视图。稍后,您将找到提供脚本的选项。

Submit the UI policy, open it again and then, click on the advanced view. Later, you will find the option to give the script.

when to apply this

此脚本将自动填充 function onCondition()。一旦我们给定的 UI 策略条件满足,将自动执行 onCondition 函数。要记住的另一点是,有两个脚本,“如果为真执行”和“如果为假执行”。

The script is automatically populated with function onCondition(). The onCondition function will be executed automatically once, the condition we have given in UI policy is met. Another point to note is that there are two scripts, “Execute if true” and “Execute if false”.

当条件匹配时,“如果为真则执行”脚本将执行一次;如果我们更改字段中的值,使得所述条件不再满足,则将执行“如果为假则执行”中的脚本。

The ‘execute if true’ script will execute once the condition is matched and if, we change the values in the fields such that, condition we have mentioned is no longer met, then the script in ‘execute if false’ will execute.

我们为两者编写一个脚本。这里,我们将使用 setValue 和 clearValue 方法。要获取字段名(需要在脚本中提及),请打开事件表单并右键单击所需的字段,你可以在“显示 - <字段名>”格式中找到字段名。

Let’s write a script for both. Here, we will use setValue and clearValue methods. To get the field name, which needs to be mentioned in the script, open the incident form and right click on the desired field, you can find the field name in format “Show - <fieldname>”

execute files

On true script

On true script

function onCondition() {
   g_form.clearValue('description');
   g_form.setValue(‘description’,'**Please mention server name, instance name and error code**');
}

On false script

On false script

function onCondition() {
   g_form.clearValue('description');
}
run script

现在,打开事件表单并查看结果。

Now, open the incident form and check the result.

run script1

Server Side Scripting

服务器端脚本在 ServiceNow 服务器或数据库上执行。服务器端脚本具有两个类别−

Server-side scripts execute on the ServiceNow server or database. Server side scripting has two categories −

  1. Business rules

  2. Script include

让我们逐个研究每个类别。

Let us take a look into each category one by one.

Business rules

业务规则模块可以在系统定义应用程序中找到。要创建业务规则,请单击“新建”。我们可以使用业务规则操作创建简单的业务规则,该操作有一个简单的下拉界面。

The business rules module can be found in System definition application. To create a business rule, click on new. We can create a simple business rule using business rule actions, which have a simple dropdown interface.

你可以使用业务规则操作来设置字段的值或在表单中添加消息。我们可以选择在以下情况下运行业务规则:

You can use business rule action to set the values of the field or to add a message in the form. We can choose, when to run the business rule as below −

  1. Before − The logic in business rule executes before the database operation

  2. After − The logic in the business rule executes after the database operation

  3. Async − Async Business Rules executes their logic after a database operation occurs but the scheduler queues the task to be run as soon as possible but not necessarily immediately after the database operation.

  4. Display − Display Business Rules executes their logic, when a form loads and a record is loaded from the database.

我们还可以选择业务规则应该执行的数据库操作。让我们在上一节创建的前端 IT 团队 ROTA 应用程序中创建业务规则操作。

We can also choose the database operation, at which the business rule should execute. Let us create a business rule action, in the Frontend IT team ROTA application, we created in the last section.

如果轮班时间为凌晨 12 点至凌晨 6 点,则必须将备注字段中的值设置为“监视 XO887 批处理作业”。输入名称和表 frontend_it_rota。在内部,选择“何时运行”选项卡,给出条件(班次为凌晨 12 点至凌晨 6 点)并勾选“插入”和“更新”框。

We have to set the value in the Remark field as “Monitor XO887 batch jobs” if the shift timing is 12am to 6am. Give the name and table frontend_it_rota. Inside, when to run tab give the condition, as shift is 12am to 6am and check ‘insert’ and ‘update’ box.

server side scripting

在操作选项卡内,给出备注字段的条件。

Inside Action tab give your condition for the remark field.

server side scripting1

我们还可以在此业务规则中给出自定义脚本。要开始编写自定义脚本,请勾选“高级”复选框,你将看到用于编写脚本的新“高级”选项卡。

We can also give our custom script in this business rule. To start writing the custom script, check the Advanced checkbox and you will see, the new Advanced tab to write the script.

让我们编写一个脚本,当没有给出成员、时间或日期字段时中止插入事务。为此,我们将使用“当前”和“上一个”对象。

Let us write a script, to abort the insert transaction when the member, time or date field is not given. We will use ‘current’ and ‘previous’ objects for this purpose.

(function executeRule(current, previous /*null when async*/)) {
   if((current.member = ' ') || (current.date = ' ') || (current.shift = ' '){
      current.setAbortAction(true);
   }
}
server side scripting2

Script Include

使用脚本包括,我们可以编写自定义函数或类,然后在其他脚本中多次使用它们。它们是可重复使用的脚本;我们可以在其他客户端端或服务器端脚本中使用它们。但是,只有当其他脚本明确调用它们时,它们才会执行。要创建新的脚本包含,我们有一个模块“ Script include ”,它位于“系统定义”应用程序下。单击“新建”以创建新的脚本包含。

Using script includes, we can write custom functions or classes and then, use them in other scripts as many times we need. They are sort of reusable scripts; we can use in other client-side or server side scripts. However, they get executed only, when called by the other scripts explicitly. To create a new script include, we have a module “Script include” under the “System definition” application. Click on new to create a new script include.

在脚本包含表单中,给出脚本包含的名称。API 名称字段是脚本包含的内部名称,当从其他应用程序调用此脚本包含时,将使用该字段。如果您要在客户端脚本中使用此脚本包含,请勾选客户端可调用复选框。在应用程序中,给出使用此脚本的应用程序。在“可从……访问”字段中,给出应用程序范围。

In the script include form, give the name of the script include. The API name field is the internal name of the script include and it is used, when this script include is called from other applications. Check the client callable checkbox, if you want to use this script include in client-side scripts. In the application, give the application for which this script is used. In the ‘accessible from’ field, give the application scope.

让我们为前端 IT 团队 ROTA 应用程序中的以下情况编写一个脚本。首先,我们将编写一个脚本包含,该脚本包含将检查任何字段中的无效字符。我们将定义一个函数,该函数将以字符串形式获取参数,并根据字符串中的字符返回 true 或 false。

Let us write a script for the following case in Frontend IT team ROTA application. First, we will write a script include, which will check an invalid character in any field. We will define a function, which will take the argument as a string and return true or false, based on the characters in the string.

我们将在业务规则脚本中使用此函数来验证在提交表单时(在前台 IT 团队 ROTA 应用程序中),“成员”(名称)字段中给定的值是否没有任何无效字符。

We will use this function in our business rule scripting to validate, if the value given in the Member (Name) field (in frontend IT team ROTA app), does not have any invalid character while submitting the form.

打开脚本包含模块,以下是我们将使用的脚本。

Open the script include module, below is the script which we will use.

function validatefieldcharacters(fieldinput) {
   var validcharacters = /^[a-zA-Z]+$/;
   if(fieldinput.value.match(validcharacters)) {
      return true;
   } else {
      return false;
   }
}
script include

现在,让我们写下业务规则脚本来验证成员字段。打开业务规则模块,并为我们的应用程序前端 IT 团队 ROTA 创建一个新的业务规则。

Now, let us write down the Business rule script to validate the Member field. Open business rule module and create a new business rule for our application Frontend IT team ROTA.

var memberfieldstatus = validatefieldcharacters(current.member)
   if(memberfieldstatus == false) {
   gs.addErrorMessage(" Special characters not allowed in member field");
   current.setAbortAction(true);
}
script include1

Debugging

如果我们的脚本未按预期执行,或者我们遇到一些错误,我们可以使用各种调试技术。让我们讨论我们可以调试客户端和服务器端脚本的各种方法。

We can use various debugging techniques, if our script is not performing as per the expectations, or if we are getting some error. Let’s discuss various ways in which, we can debug client side and server side script.

Debugging client scripts

调试客户端脚本的最佳方法是参考日志。Javascript 提供 jslog() 方法来在 Javascript 日志中写入消息。jslog() 方法接受消息,我们希望在参数中的日志中包含这些消息。以下是有关如何实现 jslog() 的示例。您可以在业务规则脚本中使用以下脚本。

The best way to debug the client script is referring to logs. The Javascript provides jslog() method to write messages in Javascript logs. The jslog() method accepts messages, which we want in the logs in the argument. Below is an example on, how we can implement the jslog(). You can use the below script in the business rule script.

function onLoad(){
   jslog("This log is displayed from jslog().");
   jslog("The value of Member field is = " + g_form.getValue('Member'));
}

这将在日志中给出成员字段中给定的值。在本例中,我们使用了 getvalue 方法来检索成员字段的值。现在,下一步是打开日志。转到位于右上角的设置选项,然后单击开发人员选项卡。打开“Javascript 日志和字段观察器”选项。

This will give the value given in the member field in the logs. In this case, we have used the getvalue method, to retrieve the value of the member field. Now, the next step is to turn the logs on. Go to setting option on the top right corner and click on developer tab. Turn on the “Javascript log and Field watcher” option.

debugging

JavaScript 日志将在 ServiceNow 浏览器主窗口底部的某个新部分中打开。

The JavaScript Logs will open in a new section at the bottom of the main ServiceNow browser window.

debugging1

除了 jslog() 之外,我们还可以使用 try/catch 语句,通常我们在 Javascript 中使用这些语句来调试脚本。

Apart from jslog() we can also use try/catch statements which we generally use in Javascript to debug the scripts.

Debugging server side script

调试服务器端脚本最常见的方法是使用“脚本调试器”模块。脚本调试器可用于放置断点、逐步遍历代码、查看变量值等。要访问脚本调试器,请在导航栏中找到“脚本调试器”。它位于“系统诊断”应用程序中。

The most common way of debugging server side script is using “Script debugger” module. The script debugger can be used to place breakpoints, traverse the code step by step, view value of variables, etc. To access script debugger, find “script debugger” in the navigation bar. It is present inside “System Diagnostics” application.

除此之外,我们还可以参考“应用程序日志”模块,该模块位于“系统日志应用程序”中。

Apart from this, we can also refer to “Application logs” module, which is present inside “System log application”.