In servicenow ui action, i want to cancel the change request with its change task and req also but after removing changerask set workflow. Task is not cancelled. Please provide the script
Assistant
To achieve your goal of canceling a change request along with its associated change tasks and requests in ServiceNow via a UI Action, you'll need a script that performs the following steps:
Retrieve the related change tasks and requests.
Cancel the change tasks.
Remove or reset the workflow associated with these tasks.
Cancel the change request.
Below is a sample script for a UI Action that should help you achieve this. Please make sure you adapt it as necessary to fit your specific ServiceNow configurations and requirements.
javascript
// Get the current change request record
var changeRequest = current;
// Check if the current record is not in a closed state
if (changeRequest.state != 'Closed') {
// Cancel related change tasks
var changeTask = new GlideRecord('change_task');
changeTask.addQuery('change_request', changeRequest.sys_id);
changeTask.addQuery('state', '!=', 'Closed');
changeTask.query();
while (changeTask.next()) {
// Reset the workflow for the change task if needed
// changeTask.setValue('workflow', ''); // Uncomment if you have specific logic to reset workflow
// Set the state of change task to canceled
changeTask.setValue('state', 'Cancelled'); // Ensure 'Cancelled' is the correct value for your implementation
changeTask.update();
}
// Cancel related requests if applicable
var reqItem = new GlideRecord('sc_req_item');
reqItem.addQuery('change_request', changeRequest.sys_id);
reqItem.addQuery('state', '!=', 'Closed');
reqItem.query();
while (reqItem.next()) {
// Reset the workflow for the request if needed
// reqItem.setValue('workflow', ''); // Uncomment if you have specific logic to reset workflow
// Set the state of request item to canceled
reqItem.setValue('state', 'Cancelled'); // Ensure 'Cancelled' is the correct value for your implementation
reqItem.update();
}
// Cancel the change request itself
changeRequest.setValue('state', 'Cancelled'); // Adjust 'Cancelled' to your implementation's specific state value
changeRequest.update();
}
// Add an appropriate message to inform the user
gs.addInfoMessage('Change Request and its related tasks have been cancelled.');
Notes:
Check that "Cancelled" is a valid state in your ServiceNow instance for change tasks and requests. If not, replace it with the appropriate state value.
If there are specific workflows or business logic associated with canceling tasks and requests, you might need to adjust the script accordingly.
Always test the script in a non-production environment before deploying it to production.
Consider error handling and logging to make it easier to troubleshoot any issues that arise when the script runs.
Remember to tailor the provided script to your organization's instance specifics, including correct table names, field names, and state values.