Learn Introduction to Development (CSA) with Interactive Flashcards

Master key concepts in Introduction to Development through our interactive flashcard system. Click on each card to reveal detailed explanations and enhance your understanding.

Scripting in ServiceNow

Scripting in ServiceNow is a fundamental skill for system administrators and developers that enables customization and automation of platform functionality. ServiceNow primarily uses JavaScript as its scripting language, allowing users to extend out-of-the-box features and create tailored solutions.

There are two main categories of scripts in ServiceNow: server-side and client-side. Server-side scripts execute on the ServiceNow server and include Business Rules, Script Includes, Scheduled Jobs, and UI Actions. These scripts interact with the database and perform backend operations. Client-side scripts run in the user's browser and include Client Scripts, UI Policies, and UI Scripts, which enhance user interface interactions and validate data before submission.

Business Rules are among the most commonly used server-side scripts. They trigger when records are inserted, updated, deleted, or queried, allowing administrators to automate processes and enforce business logic. Script Includes provide reusable code libraries that can be called from other scripts throughout the platform.

Client Scripts respond to user actions on forms, such as onChange events when field values change, onLoad events when forms open, and onSubmit events before form submission. UI Policies offer a code-free alternative for simple client-side requirements like making fields mandatory, visible, or read-only.

The GlideRecord API is essential for database operations, enabling scripts to query, create, update, and delete records. GlideSystem (gs) provides utility methods for logging, user information, and system properties.

Best practices for ServiceNow scripting include using appropriate script types for specific needs, avoiding global Business Rules when possible, leveraging Script Includes for reusable code, and thoroughly testing scripts in sub-production environments. Understanding the execution order of scripts and their impact on system performance is crucial for maintaining a healthy instance. Proper scripting skills enable administrators to deliver efficient solutions while maintaining system integrity.

Business Rules

Business Rules are powerful server-side scripts in ServiceNow that execute when database operations occur on specific tables. They are fundamental to automating processes and enforcing business logic within the platform. Business Rules trigger during four key database operations: Insert, Update, Delete, and Query. Each rule can be configured to run at specific timing points relative to these operations. The timing options include Before, After, and Async. Before rules execute prior to the database operation, making them ideal for data validation and field manipulation. After rules run once the database transaction completes, perfect for notifications and creating related records. Async rules run in the background, suitable for time-consuming operations that should not delay user interactions. When creating a Business Rule, administrators define conditions that determine when the rule should execute. These conditions can be simple field comparisons or complex scripted logic. The When to Run section allows precise control over execution criteria. Business Rules access current and previous record values through the current and previous objects respectively. This enables comparison of field changes and conditional logic based on modifications. Common use cases include auto-populating fields, enforcing mandatory requirements, updating related records, and triggering workflows. Best practices recommend keeping Business Rules efficient to maintain system performance. Administrators should avoid unnecessary queries within rules and use appropriate timing to prevent recursive loops. The Display option allows Business Rules to run when forms load, enabling dynamic form behavior. However, client scripts are often preferred for client-side interactions. Business Rules are managed through System Definition > Business Rules in the application navigator. Administrators can activate, deactivate, and order rules to control execution sequence when multiple rules apply to the same table and operation. Understanding Business Rules is essential for ServiceNow administrators as they form the backbone of server-side automation and data integrity enforcement.

Business Rule Actions

Business Rule Actions in ServiceNow are automated server-side scripts that execute when database operations occur on specific tables. These actions run in response to insert, update, delete, or query operations, allowing administrators to automate processes and enforce business logic across the platform.

Business Rules operate at four distinct timing points: Before, After, Async, and Display. Before rules execute prior to the database operation, making them ideal for data validation and field manipulation. After rules run following the database commit, perfect for triggering notifications or updating related records. Async rules execute asynchronously in the background, suitable for resource-intensive operations. Display rules run when forms load, useful for calculating values shown to users.

Key components of Business Rule Actions include conditions that determine when the rule fires, such as checking if specific fields have changed or contain certain values. The script section contains the actual JavaScript code that performs the desired action. Administrators can use the current object to reference the record being processed and previous to access field values before changes were made.

Common use cases include automatically populating fields based on other field values, preventing record updates that violate business policies, creating related records when specific conditions are met, and sending notifications when important changes occur. For example, a Business Rule might automatically set a priority field based on the impact and urgency values selected by a user.

Best practices recommend keeping Business Rules efficient to maintain system performance. Administrators should use conditions rather than scripted if-statements when possible, avoid unnecessary database queries within rules, and consider using Flow Designer for complex automation scenarios. Understanding Business Rule Actions is essential for ServiceNow administrators as they form the foundation of server-side automation and data integrity enforcement throughout the platform.

Client Scripts

Client Scripts are a fundamental component in ServiceNow that execute JavaScript code on the client-side (user's web browser) rather than on the server. They are used to enhance the user experience by providing real-time validation, field manipulation, and dynamic form behavior when users interact with forms.

There are four main types of Client Scripts:

1. **onLoad**: Executes when a form is first loaded. This is useful for setting default values, hiding or showing fields, or making fields mandatory based on certain conditions when the record opens.

2. **onChange**: Triggers when a specific field value changes. This allows developers to create dynamic responses, such as populating related fields, showing alerts, or modifying form elements based on user input.

3. **onSubmit**: Runs when a user attempts to save or submit a form. This type is commonly used for validation purposes, ensuring required data is entered correctly before the record is saved to the database.

4. **onCellEdit**: Executes when a cell is edited in a list view, enabling validation and manipulation at the list level.

Key considerations when working with Client Scripts include:

- **Performance**: Since they run in the browser, excessive or poorly written Client Scripts can slow down form loading and user interactions.

- **g_form API**: ServiceNow provides the GlideForm API (g_form) for interacting with forms, allowing developers to get and set field values, show or hide fields, and display messages.

- **g_user API**: This provides access to current user information like name, roles, and user ID.

- **Best Practices**: Keep Client Scripts lightweight, use UI Policies for simple show/hide and mandatory requirements, and avoid unnecessary server calls.

Client Scripts are essential for creating intuitive, responsive forms that guide users through data entry while maintaining data quality and improving overall system usability.

Client Script Types

Client Scripts in ServiceNow are JavaScript code that runs on the client-side (in the user's web browser) to enhance form functionality and user experience. There are four main types of Client Scripts that every ServiceNow Administrator should understand.

**1. onLoad Client Scripts**
These scripts execute when a form is first loaded in the browser. They are commonly used to set default field values, hide or show form sections, make fields mandatory, or display informational messages to users when they open a record.

**2. onChange Client Scripts**
These scripts trigger when a specific field value changes on the form. They are useful for creating dynamic form behavior, such as populating related fields based on a selection, validating field entries in real-time, or showing alerts when certain values are selected.

**3. onSubmit Client Scripts**
These scripts run when a user attempts to save or submit a form. They are primarily used for form validation before the data is sent to the server. If validation fails, the script can prevent the form submission and display an error message to the user.

**4. onCellEdit Client Scripts**
These scripts execute when a user edits a cell in a list view using list editing functionality. They allow validation and dynamic behavior when users make changes through the list interface rather than opening the full form.

**Key Considerations:**
- Client Scripts only run in the browser and do not execute during server-side operations like imports or web service calls
- They should be kept lightweight to maintain good form performance
- Use the g_form API to interact with form elements and the g_user API to access current user information
- Always specify the table and conditions carefully to ensure scripts run only when needed

Understanding these Client Script types enables administrators to create responsive, user-friendly forms that guide users through data entry effectively.

UI Policies vs Client Scripts

UI Policies and Client Scripts are both client-side tools in ServiceNow that control form behavior, but they serve different purposes and have distinct characteristics.

UI Policies are declarative, no-code solutions designed for administrators to manage form field behavior. They allow you to make fields mandatory, read-only, or visible/hidden based on specific conditions. UI Policies are easier to create and maintain because they use a point-and-click interface rather than requiring JavaScript knowledge. They execute in a specific order based on their order field value and can be set to run on form load, on change, or both. UI Policies are ideal for simple field manipulations and are generally recommended as the first choice for basic form control needs.

Client Scripts, on the other hand, are code-based solutions that require JavaScript programming. They offer much more flexibility and power, allowing developers to perform complex operations such as field validation, asynchronous server calls using GlideAjax, alert messages, and manipulation of multiple fields simultaneously. Client Scripts come in four types: onLoad (runs when form loads), onChange (triggers when a specific field value changes), onSubmit (executes before form submission), and onCellEdit (runs when list editing occurs).

Key differences include:

1. Complexity: UI Policies handle simple scenarios; Client Scripts manage complex logic.

2. Skill requirement: UI Policies need no coding; Client Scripts require JavaScript expertise.

3. Performance: UI Policies are generally lighter weight and execute after Client Scripts.

4. Execution order: Client Scripts run before UI Policies, which can override Client Script field settings.

5. Maintenance: UI Policies are easier to troubleshoot and modify.

Best practice recommends using UI Policies whenever possible for maintainability, reserving Client Scripts for scenarios requiring advanced functionality that UI Policies cannot accomplish.

UI Actions

UI Actions in ServiceNow are powerful configuration elements that allow administrators and developers to add interactive buttons, links, and context menu items to forms and lists throughout the platform. These actions enable users to perform specific operations with a single click, streamlining workflows and enhancing user productivity.

UI Actions consist of two primary components: the action definition and the associated script. The action definition determines where and how the action appears, including its name, visibility conditions, and placement. The script contains the server-side or client-side code that executes when the action is triggered.

There are several types of UI Actions based on their location and behavior. Form buttons appear at the top or bottom of record forms, allowing users to perform actions on individual records. Form links display as hyperlinks within forms. Form context menu items appear when users right-click on a form. List buttons and links provide similar functionality for list views, enabling bulk operations on multiple records.

Key properties of UI Actions include the Name field, which identifies the action, and the Table field, which specifies where the action applies. The Action name property defines the unique identifier used in scripts. The Condition field allows administrators to control when the action appears using JavaScript expressions or simple field conditions.

UI Actions can execute client-side scripts, server-side scripts, or both. Client-side scripts run in the users browser and are useful for validations and confirmations before submission. Server-side scripts execute on the ServiceNow server and handle database operations and complex business logic.

Security is managed through roles and conditions. Administrators can restrict UI Actions to specific user roles, ensuring only authorized personnel can perform certain operations. The Active checkbox allows quick enabling or disabling of actions during development or troubleshooting.

Common use cases include creating custom approval buttons, implementing record cloning functionality, and adding navigation shortcuts to related records.

Script Includes

Script Includes are powerful server-side JavaScript functions in ServiceNow that provide reusable code libraries accessible throughout the platform. They serve as a centralized repository for custom functions and classes that can be called from various server-side scripts, including Business Rules, Scheduled Jobs, UI Actions, and other Script Includes.

Key characteristics of Script Includes include:

1. **Reusability**: Instead of duplicating code across multiple scripts, you can write a function once in a Script Include and call it whenever needed. This promotes the DRY (Don't Repeat Yourself) principle and simplifies maintenance.

2. **On-Demand Loading**: Script Includes are loaded only when explicitly invoked, which improves system performance compared to having code execute on every transaction.

3. **Client Callable Option**: By checking the 'Client callable' checkbox, Script Includes can be accessed from client-side scripts using GlideAjax, enabling asynchronous server calls from the browser.

4. **API Access**: Script Includes have full access to server-side APIs like GlideRecord, GlideSystem (gs), and GlideDateTime, making them ideal for complex data operations.

5. **Extending Classes**: You can create Script Includes that extend the AbstractAjaxProcessor class for client-callable functionality or extend other custom classes for object-oriented programming approaches.

To create a Script Include, navigate to System Definition > Script Includes and click New. You must provide a name (which becomes the class name), specify the API name, and write your JavaScript code. The standard structure uses a prototype pattern with an initialize function and type property.

Best practices include using descriptive naming conventions, adding comprehensive comments, implementing proper error handling, and organizing related functions within logical Script Includes. Testing Script Includes can be done through the Scripts - Background module or by creating test Business Rules.

Script Includes are fundamental for ServiceNow development, enabling cleaner architecture, better code organization, and improved application maintainability across your instance.

GlideRecord Basics

GlideRecord is the fundamental JavaScript class used in ServiceNow for database operations. It serves as the primary method for querying, inserting, updating, and deleting records from tables in the ServiceNow platform.

Key Concepts:

1. **Creating a GlideRecord Object**: To work with a table, you first instantiate a GlideRecord object by passing the table name as a parameter. For example: var gr = new GlideRecord('incident');

2. **Querying Records**: Use the addQuery() method to specify conditions, then call query() to execute. Common methods include:
- addQuery('field', 'value') - adds a condition
- addEncodedQuery() - uses encoded query strings
- query() - executes the database query

3. **Iterating Through Results**: The next() method moves through returned records one at a time. A typical pattern uses a while loop: while(gr.next()) { // process each record }

4. **Accessing Field Values**: Use dot notation to access fields. For display values, use getDisplayValue(). For actual values, use getValue() or reference the field name.

5. **CRUD Operations**:
- Create: Use initialize() followed by insert()
- Read: Use query() and next()
- Update: Modify field values and call update()
- Delete: Use deleteRecord() to remove records

6. **Important Methods**:
- get() - retrieves a single record by sys_id
- getRowCount() - returns the number of records
- setLimit() - restricts the number of returned records
- orderBy() / orderByDesc() - sorts results

7. **Best Practices**: Always use addQuery() before query() to avoid retrieving all records. Consider performance implications when working with large datasets. Use GlideRecord in server-side scripts like Business Rules, Script Includes, and Scheduled Jobs.

GlideRecord is essential knowledge for ServiceNow administrators and developers, forming the backbone of most custom scripting solutions on the platform.

GlideSystem (gs) Methods

GlideSystem, commonly referred to as 'gs', is a powerful server-side class in ServiceNow that provides access to system-level information and utility methods. As a System Administrator or Developer, understanding gs methods is essential for scripting and automation tasks.

The gs object is available in all server-side scripts, including Business Rules, Script Includes, Scheduled Jobs, and UI Actions. It offers numerous methods categorized into several functional areas.

**User and Session Methods:**
- gs.getUserID() - Returns the sys_id of the current user
- gs.getUserName() - Returns the username of the logged-in user
- gs.hasRole('role_name') - Checks if the current user has a specific role
- gs.getUser() - Returns a GlideUser object with detailed user information

**Logging and Debugging:**
- gs.log('message') - Writes to the system log
- gs.info('message') - Logs informational messages
- gs.warn('message') - Logs warning messages
- gs.error('message') - Logs error messages
- gs.debug('message') - Logs debug-level messages

**Date and Time Methods:**
- gs.now() - Returns current date and time
- gs.nowDateTime() - Returns current date-time in system format
- gs.daysAgo(days) - Returns a date from specified days in the past
- gs.beginningOfLastMonth() - Returns the start of the previous month

**System Properties and Information:**
- gs.getProperty('property_name') - Retrieves system property values
- gs.setProperty('name', 'value') - Sets system property values
- gs.tableExists('table_name') - Checks if a table exists

**Message and Event Methods:**
- gs.addInfoMessage('text') - Displays an info message to users
- gs.addErrorMessage('text') - Displays an error message
- gs.eventQueue('event_name', record, parm1, parm2) - Queues an event

These methods form the foundation of ServiceNow server-side scripting, enabling administrators to create dynamic, user-aware, and context-sensitive solutions.

Update Sets

Update Sets are a crucial feature in ServiceNow that allow administrators and developers to group and track customizations made to an instance, enabling the organized transfer of changes between different environments such as Development, Test, and Production. When you modify configurations like business rules, UI policies, client scripts, or other application files, ServiceNow automatically captures these changes in the currently selected Update Set. By default, all changes go into the Default update set, but best practice recommends creating custom Update Sets for specific projects or features to maintain organized change management. To create an Update Set, navigate to System Update Sets and select Local Update Sets, then click New. Give it a meaningful name that describes the changes it will contain. Once created, you must set it as your current Update Set before making modifications. The system tracks insertions, updates, and deletions of records in tables that are flagged for update set tracking. After completing your customizations, you close the Update Set to prevent further modifications. The closed Update Set can then be exported as an XML file and imported into target instances. On the target instance, you preview the Update Set to identify potential conflicts or issues before committing the changes. The preview process compares incoming changes with existing configurations and highlights problems that need resolution. Common issues include missing parent records or version conflicts with existing customizations. After resolving any preview problems, you commit the Update Set to apply all changes to the target instance permanently. Update Sets support collision detection, allowing administrators to identify when multiple developers modify the same record. This feature is essential for maintaining system integrity across environments and ensuring consistent deployments. Understanding Update Sets is fundamental for any ServiceNow administrator managing multiple instances and implementing proper change management procedures throughout the application lifecycle.

Update Set Management

Update Set Management is a critical feature in ServiceNow that allows administrators to track, organize, and migrate customizations and configurations between different instances. An update set is essentially a container that groups all changes made to an instance, making it possible to move these modifications from development to test and production environments in a controlled manner.

When you make changes in ServiceNow, such as creating new fields, modifying forms, adding business rules, or updating workflows, these changes are captured in the currently selected update set. By default, ServiceNow uses a Default update set, but best practice recommends creating specific update sets for each project or feature being developed.

The update set lifecycle involves several stages. First, you create an update set and set it as your current working set. As you make changes, ServiceNow automatically records each modification as a customer update within that set. Once development is complete, you mark the update set as complete, which prevents further modifications.

To migrate changes, you retrieve the completed update set from the source instance to the target instance. The retrieval process creates a local copy that can be previewed before committing. During preview, ServiceNow identifies potential conflicts, such as when the same record was modified in both instances. Administrators must resolve these conflicts by choosing to skip, accept local changes, or accept remote changes.

After resolving conflicts, you commit the update set, which applies all changes to the target instance. Update sets also support backing out committed changes if issues arise after deployment.

Key management features include batch update sets for grouping related sets, update set comparisons, and the ability to merge multiple sets. Proper update set management ensures consistent deployments, maintains audit trails of all changes, and supports organized development practices across the ServiceNow platform lifecycle.

Application Repository

The Application Repository in ServiceNow is a centralized storage location where applications, plugins, and updates are managed and distributed across ServiceNow instances. It serves as a critical component for administrators and developers working within the ServiceNow platform.

The Application Repository functions as a catalog that contains both ServiceNow-provided applications and custom applications developed by organizations. When you access the repository through the ServiceNow Store or your instance's application manager, you can browse available applications, review their features, and install them as needed.

For System Administrators, the Application Repository provides several key capabilities. First, it enables streamlined application management by allowing administrators to view all installed applications, check for available updates, and manage application dependencies. Second, it facilitates version control by maintaining different versions of applications, making it possible to roll back to previous versions if issues arise after an update.

From a development perspective, the Application Repository supports the application lifecycle management process. Developers can publish their custom applications to the repository, making them available for deployment across multiple instances. This is particularly useful in enterprise environments where applications need to be promoted from development to testing and production environments.

The repository integrates with ServiceNow's update set functionality and application scoping features. Applications stored in the repository maintain their scope boundaries, ensuring that customizations remain organized and conflicts between applications are minimized.

Administrators can access the Application Repository through System Applications module in the navigator. From there, they can search for specific applications, filter by category or vendor, and initiate installations or updates. The repository also displays licensing information and compatibility requirements for each application.

Understanding the Application Repository is essential for maintaining a healthy ServiceNow environment, as it provides the foundation for extending platform functionality while keeping applications organized and properly versioned.

Integration Overview

Integration Overview in ServiceNow refers to the methods and technologies used to connect the ServiceNow platform with external systems, applications, and data sources. As a System Administrator, understanding integrations is crucial for creating a seamless flow of information across your organization's IT ecosystem.

ServiceNow provides several integration capabilities:

**REST APIs**: Representational State Transfer APIs allow ServiceNow to communicate with external systems using standard HTTP methods (GET, POST, PUT, DELETE). ServiceNow offers both inbound REST APIs (allowing external systems to access ServiceNow data) and outbound REST messages (allowing ServiceNow to call external services).

**SOAP Web Services**: Simple Object Access Protocol provides another method for system-to-system communication, particularly useful when integrating with legacy systems that rely on XML-based messaging.

**Import Sets and Transform Maps**: These tools enable bulk data imports from external sources. Import Sets temporarily store incoming data, while Transform Maps define how that data maps to target tables in ServiceNow.

**MID Server**: The Management, Instrumentation, and Discovery Server acts as a proxy between ServiceNow and your internal network resources. It enables secure communication with systems behind firewalls and facilitates discovery operations.

**IntegrationHub**: This is ServiceNow's workflow-based integration platform that provides pre-built spokes (connectors) to popular third-party applications, reducing development time significantly.

**Data Sources**: These define connections to external databases or files, specifying how ServiceNow retrieves data for import operations.

**Scripted Integrations**: Using JavaScript, developers can create custom integrations through Business Rules, Script Includes, and Scheduled Jobs.

Key considerations for integrations include authentication methods (Basic Auth, OAuth, API keys), data transformation requirements, error handling, and performance optimization. Proper integration design ensures data consistency, reduces manual entry, and automates cross-platform workflows, making it essential knowledge for ServiceNow professionals.

REST APIs in ServiceNow

REST APIs in ServiceNow provide a powerful way to interact with the platform programmatically, enabling integration with external systems and applications. REST (Representational State Transfer) is an architectural style that uses standard HTTP methods to perform operations on resources.

ServiceNow offers two main types of REST APIs:

1. **Inbound REST APIs**: These allow external systems to communicate with ServiceNow. The platform provides several out-of-box APIs including the Table API, Aggregate API, Import Set API, and Attachment API. The Table API is most commonly used, allowing CRUD (Create, Read, Update, Delete) operations on ServiceNow tables using HTTP methods: GET (retrieve), POST (create), PUT/PATCH (update), and DELETE (remove).

2. **Outbound REST APIs**: These enable ServiceNow to call external web services. You can configure REST Messages in ServiceNow to define endpoints, authentication, and HTTP methods for communicating with third-party systems.

**Key Components**:
- **Endpoints**: URLs that identify specific resources (e.g., /api/now/table/incident)
- **HTTP Methods**: Define the action to perform
- **Headers**: Contain metadata like Content-Type and authentication tokens
- **Request/Response Body**: Data exchanged, typically in JSON or XML format

**Authentication Methods**:
ServiceNow supports Basic Authentication, OAuth 2.0, and API keys to secure REST communications.

**Scripted REST APIs**:
For custom requirements, administrators can create Scripted REST APIs, defining custom endpoints and logic using server-side JavaScript.

**Best Practices**:
- Use appropriate authentication mechanisms
- Implement proper error handling
- Apply access controls through ACLs
- Monitor API usage through transaction logs
- Use pagination for large data sets

REST APIs are essential for ServiceNow administrators and developers as they facilitate seamless data exchange between ServiceNow and other enterprise systems, supporting automation and workflow integration across the organization.

Debugging and Logging

Debugging and Logging are essential skills for ServiceNow administrators and developers to troubleshoot issues and monitor system behavior effectively.

**Debugging** in ServiceNow refers to the process of identifying and resolving errors in scripts, workflows, and configurations. ServiceNow provides several built-in tools to help with this process. The Script Debugger allows developers to set breakpoints, step through code line by line, and inspect variable values during execution. This tool is invaluable when working with Business Rules, Script Includes, and other server-side scripts.

**Logging** involves recording information about system operations, user actions, and script execution. ServiceNow offers multiple logging mechanisms:

1. **gs.log()** - Writes messages to the system log, useful for general debugging purposes.

2. **gs.info()**, **gs.warn()**, **gs.error()** - These methods write to the system log with different severity levels, helping categorize messages appropriately.

3. **gs.debug()** - Creates debug-level log entries that can be filtered based on debugging settings.

4. **System Logs** - Accessible through System Logs > All in the navigator, these capture various system events and script outputs.

5. **Session Debug Modules** - Enable specific debugging options like Debug Business Rules, Debug Security, or Debug SQL to track particular operations during your session.

**Best Practices:**
- Use appropriate log levels to categorize message importance
- Include meaningful context in log messages such as record sys_ids and variable values
- Remove or disable debug statements before promoting code to production
- Utilize try-catch blocks to handle exceptions gracefully
- Review logs regularly to identify patterns and potential issues

Effective debugging and logging practices help maintain system stability, reduce troubleshooting time, and ensure smooth ServiceNow implementations. These skills are fundamental for both administrators managing configurations and developers creating custom applications.

More Introduction to Development questions
480 questions (total)