Client Script - OnCellEdit with Realtime Scenarios and Use Cases

In ServiceNow, the ability to use client scripts to improve data processing and user interactions is one of its strong points. When a cell in a list is edited in list view, developers can run custom logic using the OnCellEdit client script, which makes it very helpful.

In order to illustrate the practical applications of the OnCellEdit client script, in this article we go deep, providing real-time scenarios and use cases.

OnCellEdit client

ServiceNow Client Scripts

In ServiceNow, client scripts communicate with the ServiceNow instance by running in the user's browser.

They can be applied to many different tasks, such as field manipulation, form validation, and user interface improvements. When a user edits a cell in a list (List view), the OnCellEdit client script is activated, giving them the chance to carry out operations like data validation, default value setting, or dynamically altering field properties.

Key Features of the OnCellEdit Client Script

  • Trigger Event: Activates when a cell in a list is edited.
  • Field-specific Logic: Executes code specific to the cell that has been edited.
  • Provides instant feedback and updates without requiring a page reload.

Creating an OnCellEdit Client Script

To create an OnCellEdit client script in ServiceNow.

  1. Navigate to System Definition > Client Scripts.
  2. Click New to create a new script.
  3. Set the Type to OnCellEdit.
  4. Specify the Table and Field that the script will monitor.
  5. Write the Script to define the behavior when the cell is edited.in listview.

Real-Time Scenarios and Use Cases
 

1. Auto-Populating Fields Depending on Selection Scenario

When a cell's value is edited, related fields are automatically filled in.

Use Case: The Assignment Group ought to be automatically adjusted in accordance with the updated state whenever a user modifies the State field in an Incident list.

Example of Script

function onCellEdit(sysIDs, table, fieldName, newValue) {
    if (fieldName == 'state') {
        var gr = new GlideRecord('incident');
        gr.addQuery('sys_id', 'IN', sysIDs.join(','));
        gr.query();
        while (gr.next()) {
            if (newValue == 'Resolved') {
                gr.setValue('assignment_group', 'Resolved Group');
            } else if (newValue == 'In Progress') {
                gr.setValue('assignment_group', 'Support Group');
            }
            gr.update();
        }
    }
}

2. Cell Edit-Based Dynamic Field Updates

Using the edited cell value as a basis, dynamically update other fields.

Use Case: When editing the Priority field on a Change Request list, the Risk field needs to be updated to reflect the new priority.

Example of Script

function onCellEdit(sysIDs, table, fieldName, newValue) {
    if (fieldName == 'priority') {
        var gr = new GlideRecord('change_request');
        gr.addQuery('sys_id', 'IN', sysIDs.join(','));
        gr.query();
        while (gr.next()) {
            if (newValue == '1 - Critical') {
                gr.setValue('risk', 'High');
            } else if (newValue == '2 - High') {
                gr.setValue('risk', 'Medium');
            } else {
                gr.setValue('risk', 'Low');
            }
            gr.update();
        }
    }
}

3. Checking Input Using Values from Other Fields

Verify the edited cell value by comparing it to the values of other fields in the record.

Use Case: When editing a task list, make sure the Due Date isn't set earlier than the Start Date.

Example of Script

function onCellEdit(sysIDs, table, fieldName, newValue) {
    if (fieldName == 'due_date') {
        var gr = new GlideRecord('task');
        gr.addQuery('sys_id', 'IN', sysIDs.join(','));
        gr.query();
        while (gr.next()) {
            var startDate = gr.getValue('start_date');
            if (newValue < startDate) {
                gs.addErrorMessage('Due Date cannot be earlier than Start Date.');
                return false;
            }
        }
    }
}

4. Related Records Are Automatically Created

Whenever a cell is edited, a related record is automatically created.

Use Case: Create a related Problem record whenever an incident's State field is changed to Resolved.

Example of Script

function onCellEdit(sysIDs, table, fieldName, newValue) {
    if (fieldName == 'state' && newValue == 'Resolved') {
        var gr = new GlideRecord('incident');
        gr.addQuery('sys_id', 'IN', sysIDs.join(','));
        gr.query();
        while (gr.next()) {
            var problemGr = new GlideRecord('problem');
            problemGr.initialize();
            problemGr.incident = gr.sys_id;
            problemGr.short_description = 'Problem related to Resolved Incident: ' + gr.number;
            problemGr.insert();
        }
    }
}

5. Logic for Workflow Actions with Conditions

Determine which actions to take in response to the modified cell value.

Use Case: Alert the Change Manager if the Change Type field on a list of Change Requests is changed to Emergency.

Example of Script

function onCellEdit(sysIDs, table, fieldName, newValue) {
    if (fieldName == 'change_type' && newValue == 'Emergency') {
        var gr = new GlideRecord('change_request');
        gr.addQuery('sys_id', 'IN', sysIDs.join(','));
        gr.query();
        while (gr.next()) {
            var changeManager = gr.change_manager.getDisplayValue();
            gs.eventQueue('change_request.emergency', gr, changeManager, 'A Change Request has been marked as Emergency.');
        }
    }
}

Guidelines for Using Client Scripts for OnCellEdit

  1. To preserve readability and performance, OnCellEdit scripts should not contain excessively complicated logic.
  2. Include comments in your code that describe the function and goal of each section.
  3. Prior to deploying OnCellEdit scripts to production, make sure they have been tested thoroughly in a development or test environment like dev instances.
  4. Give users clear error messages that instruct them on what needs to be fixed.
  5. OnCellEdit client script is an effective tool for streamlining user interactions and streamlining workflow automation. You can generate dynamic field updates, validate data instantly, and optimize procedures throughout your ServiceNow instance by utilizing this feature.
  6. The OnCellEdit script provides a flexible solution for a variety of scenarios, whether you are dynamically populating fields, enforcing data integrity, or integrating with other records. To achieve optimal performance and reliability, follow best practices and make sure you test everything thoroughly, just like you would with any customization.

By following best practices, you can ensure that your scripts are efficient, maintainable, and provide a positive user experience.

Hope this was helpful, Bye until next time, and happy reading!


Similar Articles