Skip to content

Commit 36e496f

Browse files
authored
Remove element from listfield (ServiceNowDevProgram#715)
* Create removeFromList.js Code to remove element from a list field * Create readme.md Add some documentation about the code, usage and community reference.
1 parent 854a1e2 commit 36e496f

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
This script can be used to remove a specific element from a list field across multiple records in a table that match a query condition.
2+
3+
It requires 3 variables to be set:
4+
- table {string}: the name of the table to run on, e.g. 'kb_knowledge_block'
5+
- listField {string}: the name of the list field on the above table to remove an element from, e.g. 'can_read_user_criteria'
6+
- whatToRemove {sysId}: the sys_id of the element to remove from the list field, e.g. sys_id of a specific user critria
7+
8+
The script contains additional inline comments about what it does while runnning.
9+
10+
Further context annd use case can be read in the [related community post](https://www.servicenow.com/community/developer-forum/glide-list-type-field-need-to-remove-one-value-in-bulk/m-p/2431257#M947276) where this code was used as the solution by yours truly.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
var table = ''; // Name of the table, e.g. kb_knowledge_block
2+
var listField = ''; // Name of the list field to remove an element from, e.g. can_read_user_criteria
3+
var whatToRemove = ''; // Sys_id of the element to remove from the list field, e.g. sys_id of user criteria
4+
var encQ = listField + 'LIKE' + whatToRemove; // encoded query to limit queried record to those that contain the element we want to remove
5+
var listArray = []; // initial array variable declaration
6+
var elementIndex = -1; // initial index variable declaration
7+
8+
9+
/* Run a GlideRecord query to find all records that contain the element to be deleted from the specifid list field */
10+
var listGr = new GlideRecord(table);
11+
listGr.addEncodedQuery(encQ);
12+
listGr.query();
13+
while(listGr.next()) {
14+
listArray = listGr[listField].toString().split(','); // set the array variable based on the List field of the found record
15+
elementIndex = listArray.indexOf(whatToRemove); // search for the element to remove from this particular record
16+
/* Only try to remove the element and update the record if it was found, i.e. not -1 */
17+
if(elementIndex > -1) {
18+
listArray.splice(elementIndex,1);
19+
listGr.setValue(listField,listArray);
20+
listGr.update();
21+
}
22+
/* Reset the initial array related variables */
23+
listArray = [];
24+
elementIndex = -1;
25+
}

0 commit comments

Comments
 (0)