Skip to content

Commit 5748f61

Browse files
Dynamically Switch Form View Based on Field Value on the form (ServiceNowDevProgram#1674)
* Create README.md * Create dynamic-form-view-onchange.js Add the code * Update dynamic-form-view-onchange.js * Update README.md
1 parent 968626b commit 5748f61

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
## Dynamically Switch Form View Based on Field Value
2+
3+
This client script demonstrates how to **automatically switch form views** based on the value of a field.
4+
5+
**Use case:**
6+
For example, if the **Category** field is set to *Hardware*, the form view switches to **ess**.
7+
You can extend this by updating the mapping object to support additional fields and values (e.g., *Software → itil*, *Network → support*).
8+
9+
**Benefit:**
10+
Improves user experience by guiding users to the **most relevant form view**, ensuring the right fields are shown for the right scenario.
11+
12+
**Test:**
13+
- Change the **Category** field to *Hardware* → Form view should switch to **ess**.
14+
- Update mapping to add new conditions (e.g., *Software → itil*) and verify the view switches accordingly.
15+
16+
**How to Use:**
17+
1. **Modify the table name** in the `switchView` function to match your target table:
18+
```javascript
19+
switchView("section", "<your_table_name>", targetView);
20+
2. **Modify the view mapping**
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* dynamic-form-view-onchange.js
3+
*
4+
* Dynamically switches the form view automatically depending on the value of a specific field.
5+
* Example: If Category = Hardware → switch to ess view.
6+
* Extendable by modifying the mapping object for different fields/values.
7+
*
8+
*/
9+
10+
function onChange(control, oldValue, newValue, isLoading) {
11+
if (isLoading || !newValue) {
12+
return;
13+
}
14+
15+
// Field value → view name mapping
16+
var viewMapping = {
17+
"hardware": "ess",
18+
"software": "itil",
19+
"network": "support"
20+
};
21+
22+
var fieldValue = newValue.toLowerCase();
23+
var targetView = viewMapping[fieldValue];
24+
25+
if (targetView) {
26+
try {
27+
// Here for example the table name is incident
28+
switchView("section", "incident", targetView);
29+
} catch (e) {
30+
console.error("View switch failed: ", e);
31+
}
32+
}
33+
}

0 commit comments

Comments
 (0)