본문 바로가기
ICT

[ServiceNow] Business Rule to Change Task States

by NeoSailer 2023. 12. 13.

[Requirements]

Automation - Automatically move Change Request from Implement to Review

Automatically move Change Request from Implement to Review when Change Tasks are closed. 

 

[OS] 

N/A

 

[Development Language]

JavaScript

 

[IDE]

Web browser

 

[Settings]

In ServiceNow, go to "Business Rule" then go to "When to run"

- When: after

- Insert, Update checked

- Filter Conditions: "State" changes to "Closed"

 

Write code in "Advanced" tab

 

[Code]

(function executeRule(current, previous /*null when async*/) {

	// Variables
	var ct_closed = true;
	var ct_closed_successful = true;	
	var counter = 0;

	// Get parent change task
	var cr = new GlideRecord('change_request');
	cr.get(current.change_request);
	cr.query();
		
	// Get the change tasks under the parent task
	var ct = new GlideRecord('change_task');	
	ct.addQuery('parent', cr.sys_id); // getting sub tasks under nearth the parent task
	ct.query();	

	while(ct.next())
	{
		// Check all change task whether it is closed	
		if(ct.state != 3)
		{
			ct_closed = false;
		}		
	}
    
	// if all sub tasks are closed, change state to "Review"
	if(ct_closed == true)
	{	
		// Change state to "Review"		
		cr.state = 0;
		cr.work_notes = 'State has been changed to "Review" after all sub-tasks are closed successfully';					
		cr.update();						
	}
})(current, previous);

 

 

 

[Test]

 

Works as intended

 

[Lesson Learned]

 

Took days to figure out how to get sub tasks under a parent task.

When getting sub-tasks with code below, it fetches all change tasks.

var ct = new GlideRecord("change_task")
ct.addQuery("change_request", current.sys_id);
ct.query();

 

Working codes are as below.

// Get parent change task
var cr = new GlideRecord('change_request');
cr.get(current.change_request);
cr.query();

// Get the change tasks under the parent task
var ct = new GlideRecord('change_task');	
ct.addQuery('parent', cr.sys_id); // getting sub tasks under nearth the parent task
ct.query();

 

Do not 100% trust codes on the web...

반응형

'ICT' 카테고리의 다른 글

[ServiceNow] Modifying workflow in Workflow Editor  (0) 2023.12.19
[ServiceNow] Limit the Category Visibility  (0) 2023.12.14
Setting Up Network Printers  (0) 2023.09.20
[Windows10] Enable Microsoft Store  (0) 2023.08.24
JavaScript Learning Pathway  (0) 2023.08.11

댓글