Skip to content

Commit a21e5fd

Browse files
Merge branch 'ServiceNowDevProgram:main' into main
2 parents 5a50f65 + f900211 commit a21e5fd

File tree

42 files changed

+1002
-120
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+1002
-120
lines changed

CONTRIBUTING.md

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,25 @@ If you plan to submit another pull request while your original is still pending,
3131
- **Descriptive Pull Request Titles**: Your pull request must have explicit and descriptive titles that accurately represent the changes made.
3232
- **Scope Adherence**: Changes that fall outside the described scope will result in the entire pull request being rejected.
3333
- **Quality Over Quantity**: Low-effort or spam pull requests will be marked accordingly.
34-
- **Expanded Snippets**: Code snippets reused from the [ServiceNow Documentation](https://docs.servicenow.com/) or [API References](https://developer.servicenow.com/dev.do#!/reference/) are acceptable only if they are expanded in a meaningful way (e.g., with additional context, documentation, or variations). Remember: *QUANTITY IS FUN, QUALITY IS KEY.*
34+
- **Expanded Snippets**: Code snippets reused from the [ServiceNow Documentation](https://docs.servicenow.com/) or [API References](https://developer.servicenow.com/dev.do#!/reference/) are acceptable only if they are expanded in a meaningful way (e.g., with additional context, documentation, or variations). Remember: *"QUANTITY IS FUN, QUALITY IS KEY."*
3535
- **Relevance**: Code should be relevant to ServiceNow Developers.
3636
- **ES2021 Compatibility**: While ES2021 is allowed, we encourage you to disclose if your code is using ES2021 features, as not everyone may be working with ES2021-enabled applications.
3737

38+
## Core Documentation File Changes
39+
40+
**IMPORTANT**: For changes to core documentation files (README.md, CONTRIBUTING.md, LICENSE, etc.), contributors must:
41+
42+
1. **Submit an Issue First**: Before making any changes to core documentation files, create an issue describing:
43+
- What you intend to edit
44+
- Why the change is needed
45+
- Your proposed approach
46+
47+
2. **Get Assignment**: Wait to be assigned to the issue by a maintainer before submitting a PR.
48+
49+
3. **Reference the Issue**: Include the issue number in your PR title and description.
50+
51+
This process helps prevent merge conflicts when multiple contributors want to update the same documentation files and ensures all changes align with the project's direction.
52+
3853
## Repository Structure
3954

4055
**IMPORTANT**: The repository has been reorganized into major categories. All new contributions MUST follow this structure for PR approval.
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Field Color-Coding Based on Choice Values
2+
3+
## Purpose
4+
Dynamically change the background color of any choice field on a form based on the selected backend value.
5+
6+
## How to Use
7+
1. Create an OnChange client script on the desired choice field.
8+
2. Replace `'your_field_name'` in the script with your actual field name.
9+
3. Update the `colorMap` with relevant backend choice values and colors.
10+
4. Save and test on the form.
11+
12+
## Key Points
13+
- Works with any choice field
14+
- Uses backend values of choices for mapping colors.
15+
16+
## Demo
17+
18+
<img width="1710" height="557" alt="image" src="https://github.com/user-attachments/assets/9fb9e68a-1ade-4eb5-81cc-c947c970bd6f" />
19+
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
function onChange(control, oldValue, newValue, isLoading) {
2+
3+
var colorMap = {
4+
'1': '#e74c3c', // Critical - strong red
5+
'2': '#e67e22', // High - bright orange
6+
'3': '#f1c40f', // Moderate - yellow
7+
'4': '#3498db', // Low - blue
8+
'5': '#27ae60' // Planning - green
9+
};
10+
11+
var priorityField = g_form.getControl('priority');
12+
if (!priorityField) return;
13+
14+
priorityField.style.backgroundColor = colorMap[newValue] || '';
15+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Count Open Incidents per Priority Using GlideAggregate
2+
3+
## Overview
4+
This script dynamically calculates the **number of open incidents** for each priority level using **server-side scripting** in ServiceNow.
5+
Priority levels typically include:
6+
+ 1 – Critical
7+
+ 2 – High
8+
+ 3 – Moderate
9+
+ 4 – Low
10+
11+
The solution leverages **GlideAggregate** to efficiently count records grouped by priority. This approach is useful for:
12+
+ Dashboards
13+
+ Automated scripts
14+
+ Business rules
15+
+ SLA monitoring and reporting
16+
17+
---
18+
19+
## Table and Fields
20+
+ **Table:** `incident`
21+
+ **Fields:** `priority`, `state`
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
(function() {
2+
// Create GlideAggregate object on 'incident' table
3+
var ga = new GlideAggregate('incident');
4+
5+
// Filter only open incidents (state != Closed (7))
6+
ga.addQuery('state', '!=', 7);
7+
8+
// Group results by priority
9+
ga.groupBy('priority');
10+
11+
// Count number of incidents per priority
12+
ga.addAggregate('COUNT');
13+
14+
ga.query();
15+
16+
gs.info('Open Incidents by Priority:');
17+
18+
while (ga.next()) {
19+
var priority = ga.priority.getDisplayValue(); // e.g., Critical, High
20+
var count = ga.getAggregate('COUNT');
21+
gs.info(priority + ': ' + count);
22+
}
23+
})();
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
## Overview
2+
This script retrieves incidents that were opened more than X days ago using **GlideDateTime** and **GlideRecord**.
3+
Useful for reporting, escalations, notifications, and cleanup tasks.
4+
5+
## Table and Field
6+
- **Table:** `incident`
7+
- **Field:** `opened_at`
8+
9+
## Parameters
10+
- **X (number of days):** Defines the threshold for old incidents (e.g., 30 days).
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
(function() {
2+
var days = 30; // Change this to your required number of days
3+
4+
// Calculate the date X days ago
5+
var cutoffDate = new GlideDateTime();
6+
cutoffDate.addDaysUTC(-days);
7+
8+
// Query incidents opened before the cutoff date
9+
var gr = new GlideRecord('incident');
10+
gr.addQuery('opened_at', '<', cutoffDate);
11+
gr.query();
12+
13+
gs.info('Incidents opened more than ' + days + ' days ago:');
14+
15+
while (gr.next()) {
16+
gs.info('Incident Number: ' + gr.number + ', Opened At: ' + gr.opened_at.getDisplayValue());
17+
}
18+
})();
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# Querying JSON with JSONPath to extract values
2+
3+
GlideJsonPath is a class which can be used to use JSONPath in ServiceNow. It can be useful when working with JSON Payloads, especially highly nested or in general complex structures.
4+
5+
References:
6+
- [RFC 9535: JSONPath: Query Expressions for JSON](https://datatracker.ietf.org/doc/rfc9535/)
7+
- [Play with JSONPath outside of ServiceNow](https://jsonpath.com/)
8+
- [Good Examples to start with](https://restfulapi.net/json-jsonpath/)
9+
- [ServiceNow API Documentation](https://www.servicenow.com/docs/bundle/zurich-api-reference/page/app-store/dev_portal/API_reference/GlideJsonPath/concept/GlideJsonPathAPI.html)
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// Run in background script
2+
var json = {
3+
"store":
4+
{
5+
"book": [
6+
{
7+
"category": "reference",
8+
"author": "Nigel Rees",
9+
"title": "Sayings of the Century",
10+
"price": 8.95
11+
},
12+
{
13+
"category": "fiction",
14+
"author": "Evelyn Waugh",
15+
"title": "Sword of Honour",
16+
"price": 12.99
17+
},
18+
{
19+
"category": "fiction",
20+
"author": "Herman Melville",
21+
"title": "Moby Dick",
22+
"isbn": "0-553-21311-3",
23+
"price": 8.99
24+
},
25+
{
26+
"category": "fiction",
27+
"author": "J. R. R. Tolkien",
28+
"title": "The Lord of the Rings",
29+
"isbn": "0-395-19395-8",
30+
"price": 22.99
31+
}
32+
],
33+
"bicycle": {
34+
"color": "red",
35+
"price": 19.95
36+
}
37+
}
38+
};
39+
40+
var path1 = 'store.book[0].author'; // The author of the first book
41+
var path2 = 'store.book[*].author'; // All authors
42+
var path3 = 'store..price'; // All prices
43+
var path4 = '$..book[?(@.price<10)]'; // All books cheaper than 10
44+
var path5 = '$..book[?(@.isbn)]'; // All books with an ISBN number
45+
var path6 = '$..*'; // All members of JSON structure
46+
47+
var gjp = new GlideJsonPath(JSON.stringify(json));
48+
gs.info('Path: ' + path1 + ' Result: ' + gjp.read(path1));
49+
gs.info('Path: ' + path2 + ' Result: ' + gjp.read(path2));
50+
gs.info('Path: ' + path3 + ' Result: ' + gjp.read(path3));
51+
gs.info('Path: ' + path4 + ' Result: ' + gjp.read(path4));
52+
gs.info('Path: ' + path5 + ' Result: ' + gjp.read(path5));
53+
gs.info('Path: ' + path6 + ' Result: ' + gjp.read(path6));

README.md

Lines changed: 85 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,20 @@
11
![Code Snippets Banner](https://github.com/ServiceNowDevProgram/code-snippets/assets/31702109/f9fa072a-4c0c-426b-8eed-200c6616ff60)
22

3+
<div align="center">
4+
5+
[![Contributions Welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat-square)](CONTRIBUTING.md)
6+
[![Hacktoberfest](https://img.shields.io/badge/Hacktoberfest-Participating-orange?style=flat-square)](https://github.com/ServiceNowDevProgram/Hacktoberfest)
7+
8+
</div>
9+
10+
# ServiceNow Code Snippets Repository
11+
312
Welcome to ServiceNow's Code Snippets community repository, managed by the Developer Program and the sndevs Slack community.
413

514
Inside this repository, you will find community submitted code-snippets and their variants for different use-cases.
615

16+
**[📝 Contribution Guidelines](CONTRIBUTING.md)** | **[📚 Browse Categories](#repository-organization)** | **[🔍 How to Use](#how-to-use-this-repository)**
17+
718
> Interested in our other ServiceNow Hacktoberfest projects? See the main repository [here](https://github.com/ServiceNowDevProgram/Hacktoberfest) or see our official blog post [here](https://devlink.sn/hacktoberfest).
819
920
**Note:** ServiceNowDevProgram has many repositories that can be imported directly into ServiceNow, this is not one of them; This repository is meant to be edited directly in GitHub or any other Git-enabled IDE like VS Code.
@@ -28,6 +39,25 @@ We appreciate your participation and contributions to this community-driven proj
2839
**_CONTRIBUTORS must follow all guidelines in [CONTRIBUTING.md](CONTRIBUTING.md)_** or run the risk of having your Pull Requests labeled as spam.<br>
2940
🔔🔔🔔
3041

42+
## Table of Contents
43+
44+
- [How to Use This Repository](#how-to-use-this-repository)
45+
- [Repository Organization](#repository-organization)
46+
- [Finding Snippets](#finding-snippets)
47+
- [Folder Structure](#folder-structure)
48+
- [Contributing](#we-invite-you-to-contribute)
49+
- [Disclaimer](#disclaimer)
50+
51+
## How to Use This Repository
52+
53+
This repository contains code snippets that you can use in your ServiceNow instance. Here's how to make the most of it:
54+
55+
1. **Browse by Category**: Navigate through the [six major categories](#repository-organization) to find snippets relevant to your needs.
56+
2. **Copy and Adapt**: Once you find a useful snippet, copy the code and adapt it to your specific use case in your ServiceNow instance.
57+
3. **Read the Documentation**: Each snippet folder contains a README.md file that explains how the snippet works and how to implement it.
58+
4. **Search by Topic**: Use GitHub's search functionality to find snippets by keywords (e.g., "GlideRecord", "REST", "UI Action").
59+
5. **Contribute Your Own**: If you have a useful snippet, consider [contributing](#we-invite-you-to-contribute) to help others.
60+
3161
## Repository Organization
3262

3363
The repository is organized into **6 major categories** that cover all aspects of ServiceNow development:
@@ -50,16 +80,65 @@ External system integrations, data import/export utilities, RESTMessageV2 exampl
5080
### 🎯 [Specialized Areas](Specialized%20Areas/)
5181
Domain-specific functionality including CMDB utilities, ITOM scripts, Performance Analytics, ATF Steps, Agile Development tools, and other specialized use cases.
5282

83+
## Finding Snippets
84+
85+
There are several ways to find the snippets you need:
86+
87+
1. **By Category**: Browse the six major categories listed above.
88+
2. **By Search**: Use GitHub's search functionality with keywords like:
89+
- API names: `GlideRecord`, `GlideSystem`, `GlideAjax`
90+
- Component types: `Business Rule`, `Client Script`, `UI Action`
91+
- Functionality: `REST`, `SOAP`, `Import`, `Export`
92+
- Use cases: `Authentication`, `Notification`, `Workflow`
93+
94+
3. **By Tags**: Many snippets include common keywords in their README files that can be searched.
95+
96+
## Folder Structure
97+
98+
The repository follows a consistent structure to make navigation easier:
99+
100+
```
101+
Top-Level Category/
102+
├── Sub-Category/
103+
│ ├── Specific Snippet/
104+
│ │ ├── README.md # Description and usage instructions
105+
│ │ ├── snippet_file.js # The actual code snippet
106+
│ │ └── variant.js # Variations of the snippet (if applicable)
107+
```
108+
109+
For example:
110+
```
111+
Core ServiceNow APIs/
112+
├── GlideRecord/
113+
│ ├── Query Performance Optimization/
114+
│ │ ├── README.md
115+
│ │ ├── basic_query.js
116+
│ │ └── optimized_query.js
117+
```
118+
53119
## We invite you to contribute!
54120

55-
To contribute, just follow these steps:
121+
We welcome contributions from the ServiceNow developer community! Your knowledge and experience can help others solve common challenges.
122+
123+
## 🌐 Contribute from the Web (No Setup Needed!)
124+
125+
This repository has been approved by Hacktoberfest in spirit of learning source control and getting started in your open-source journey. You can contribute directly from your browser without needing a ServiceNow instance:
126+
127+
1. Click **Fork** at the top-right corner of this page
128+
2. Open the folder where you want to add or edit a file
129+
3. Click **Add file → Create new file** (or edit an existing one)
130+
4. Scroll down, add a **commit message**, and select
131+
> "**Create a new branch for this commit and start a pull request**"
132+
5. Click **Propose changes → Create pull request**
133+
134+
That's it! **For detailed contribution instructions, please read our [CONTRIBUTING.md](CONTRIBUTING.md) guide before submitting.**
56135

57-
1. Fork this repo (you get a point just by forking!)
58-
2. Create a new branch on your fork
59-
3. Add/Update the repo
60-
4. Submit a pull request!
136+
### What makes a good contribution?
61137

62-
That's it! More detailed contribution instructions can be found [here](CONTRIBUTING.md)
138+
- **Useful snippets** that solve common ServiceNow development challenges
139+
- **Well-documented code** with clear comments explaining how it works
140+
- **Proper organization** following the repository structure
141+
- **Variations** of snippets for different use cases when applicable
63142

64143
## Leaderboard
65144

0 commit comments

Comments
 (0)