Client Script vs UI Policy: Choosing the Right Tool for ServiceNow Form Customization






Client Script vs. UI Policy: Mastering ServiceNow Client-Side Logic


Client Script vs. UI Policy: Mastering ServiceNow Client-Side Logic

In the world of ServiceNow development, crafting dynamic and user-friendly forms is paramount. Two powerful tools at our disposal for achieving this are Client Scripts and UI Policies. Both play a crucial role in managing form behavior and enhancing the user experience by executing logic directly in the user’s web browser. However, they differ significantly in their capabilities and when to use each one. For developers, understanding these distinctions is key to building efficient and robust applications. This article will delve deep into the nuances of Client Scripts and UI Policies, providing practical guidance to help you make the right choice for your next development project.

Understanding the Core Concepts

Client Scripts: The Power of JavaScript on the Browser

At their heart, Client Scripts are pieces of JavaScript code that run on the client-side, meaning they execute within the user’s web browser. They are triggered by specific events that occur on a form, such as when the form loads, when a user interacts with a field, or when the form is submitted. This allows for real-time validation, dynamic field manipulation, and personalized user interactions without needing to reload the entire page.

ServiceNow offers several types of Client Scripts, each designed for a particular event:

  • OnLoad Scripts: These scripts fire when a form initially loads in the browser. They are perfect for setting default values, hiding or showing fields based on initial conditions, or performing any setup required before the user even starts interacting with the form.
  • OnChange Scripts: As the name suggests, these scripts execute whenever a user changes the value of a specific field. This is invaluable for real-time validation, updating dependent fields, or triggering further actions based on user input.
  • OnSubmit Scripts: These scripts run just before a form is saved or updated to the database. They are your last line of defense for form validation, ensuring data integrity before it’s committed. You can also use them to gather additional data or perform final calculations.
  • OnCellEdit Scripts: These are less common for form-level interactions but are crucial for list editing. They execute when a user directly edits a cell within a list view, allowing for inline validation and manipulation of list data.

Example of an OnLoad Client Script:


    function onLoad() {
        // Set the default value for the "Priority" field to "Medium"
        g_form.setValue('priority', '2 - Medium');

        // If the "State" field is already set to "Closed", hide the "Close Notes" field.
        if (g_form.getValue('state') == 'closed') {
            g_form.setDisplay('close_notes', false);
        }
    }
    

Example of an OnChange Client Script:


    function onChange(control, oldValue, newValue, isLoading, isTemplate) {
        // Stop script execution if it's during form load, the new value is empty, or it's from a template
        if (isLoading || newValue == '' || isTemplate) {
            return;
        }

        // When the "Category" changes, update the "Subcategory" field
        if (control.id == 'category') {
            if (newValue == 'Hardware') {
                g_form.setValue('subcategory', 'Workstation');
            } else if (newValue == 'Software') {
                g_form.setValue('subcategory', 'Operating System');
            } else {
                g_form.setValue('subcategory', ''); // Clear if not Hardware or Software
            }
        }
    }
    

Example of an OnSubmit Client Script:


    function onSubmit() {
        // Perform a final check to ensure the "Short Description" is not empty
        if (g_form.getValue('short_description') == '') {
            g_form.showFieldMsg('short_description', 'A short description is mandatory before submitting.', 'error');
            return false; // Prevent form submission
        }

        // Set the caller to the currently logged-in user before submission
        g_form.setValue('caller_id', g_user.userID);

        return true; // Allow form submission
    }
    

UI Policies: Declarative Form Control

UI Policies offer a more declarative approach to managing form behavior. They are essentially a set of rules that dictate how form fields should behave based on certain conditions. The beauty of UI Policies lies in their ability to control field attributes like visibility, readability, and mandatory status without writing a single line of JavaScript in many cases. This makes them incredibly efficient for common form manipulations.

When a UI Policy’s condition is met, it triggers associated UI Policy Actions. These actions are what actually change the field attributes. Think of it as a “if this, then do that” mechanism for your forms.

A key advantage of UI Policies is their ability to handle visibility, mandatory, and read-only states without requiring you to write code for each attribute. This significantly speeds up development for common use cases.

Client Script vs. UI Policy: When to Use Which

The choice between a Client Script and a UI Policy often comes down to the complexity of the logic and the specific behavior you need to achieve. Here’s a breakdown based on key criteria:

CriteriaClient ScriptUI Policy
Execute on form loadYesYes
Execute on form save/submit/updateYes (OnSubmit)No
Execute on form field value changeYes (OnChange)Yes
Have access to field’s old valueYes (OnChange script parameters)No
Execute after Client ScriptsNoYes (UI Policies run after Client Scripts)
Set field attributes with no scriptingNo (Requires scripting)Yes (UI Policy Actions)
Require control over order of executionYes (Through script logic and potentially form customization to add ‘Order’)Yes (Through the ‘Order’ field)

Key Takeaways from the Table:

  • Form Save/Submit: If your logic needs to execute precisely at the moment of form submission or saving, a Client Script (OnSubmit) is your go-to. UI Policies do not directly handle this.
  • Field Attributes (Mandatory, Visible, Read-only): For simply making fields mandatory, visible, or read-only based on conditions, UI Policies are generally the more efficient and maintainable choice. They allow you to do this declaratively, without custom scripting for each attribute.
  • Access to Old Value: If you need to compare the current field value with its previous value (e.g., to audit changes or trigger logic based on a specific transition), a Client Script (OnChange) provides this information directly through its parameters.
  • Order of Execution: Both can be ordered. However, it’s crucial to remember that UI Policies execute *after* Client Scripts. This means if you have conflicting logic, the UI Policy’s behavior will often prevail. This is a vital point for troubleshooting.

Diving Deeper: Advanced Scenarios and Best Practices

When UI Policies Shine

UI Policies are excellent for:

  • Conditional Visibility: Showing or hiding fields based on the value of another field. For example, showing a “Close Notes” field only when the “State” is “Closed.”
  • Mandatory Fields: Making fields required based on specific criteria. For instance, making “Assignment Group” mandatory if the “Assigned to” field is empty.
  • Read-only Fields: Preventing users from editing fields under certain conditions. A common example is making “State” read-only once a record has reached a “Closed” or “Resolved” state.
  • Complex Conditions with Simple Actions: When you have multiple conditions that need to evaluate to true or false, and the resulting actions are simply setting field attributes, UI Policies are very clean.

Developer Tip: Always provide a descriptive value in the Short description field for your UI Policies. Since they don’t have a dedicated “Name” field like Client Scripts, a good description is crucial for identification and debugging.

When Client Scripts are Necessary

Client Scripts are your best bet when:

  • Custom Logic and Calculations: Performing complex calculations, manipulating strings, or interacting with external systems (though caution is advised with direct external calls from the client).
  • Accessing Old Field Values: As mentioned, `onChange` Client Scripts provide `oldValue` and `newValue`, which are indispensable for certain validation or audit-trail scenarios.
  • OnSubmit Validation and Data Preparation: When you need to perform final checks, set values, or display messages just before a record is saved.
  • Dynamic Choice List Manipulation: While UI Policies can influence choice lists, Client Scripts offer more granular control for adding, removing, or modifying options within choice lists.
  • Fine-grained Control over Execution Order (Beyond UI Policies): While UI Policies have an ‘Order’ field, and client scripts can be influenced by that order, Client Scripts themselves might need to control execution flow internally or interact with other client-side elements in ways UI Policies cannot.

Developer Tip: When working with `onChange` Client Scripts, always include the `if (isLoading || newValue == ”) { return; }` check at the beginning. This prevents your script from running unnecessarily during form load or when a field is cleared, which can often lead to unexpected behavior.

The `GlideForm` and `GlideUser` APIs

Both Client Scripts and UI Policy scripts leverage powerful client-side APIs. The two most fundamental are:

  • `GlideForm (g_form)`: This is your primary tool for interacting with the form itself. You’ll use it to get field values (`g_form.getValue()`), set field values (`g_form.setValue()`), make fields mandatory (`g_form.setMandatory()`), show/hide fields (`g_form.setDisplay()`), add messages (`g_form.addErrorMessage()`), and much more.
  • `GlideUser (g_user)`: This API provides information about the currently logged-in user. You can retrieve their username (`g_user.userName`), user ID (`g_user.userID`), first name (`g_user.firstName`), and crucially, check their roles (`g_user.hasRole(‘admin’)`). This is often used for personalizing the UI or restricting certain actions based on user roles.

The Execution Order: A Crucial Detail

It’s essential to understand that UI Policies execute *after* Client Scripts. This has significant implications:

  • If a Client Script sets a field to visible, and a UI Policy then runs and makes it invisible, the UI Policy’s action will take precedence.
  • If you have conflicting logic, the UI Policy’s rules will typically overwrite or supersede the Client Script’s.

This order is managed by the Order field on UI Policies. While Client Scripts don’t have a direct ‘Order’ field on their form baseline, their execution order relative to other client scripts can be influenced by dependencies and the order in which they are processed. However, their execution comes before UI Policies.

UI Policy Scripts: The Best of Both Worlds?

For more complex scenarios where UI Policies alone aren’t sufficient but you still want to leverage the UI Policy framework, UI Policy Scripts come into play. These are enabled in the ‘Advanced’ view of a UI Policy and allow you to write JavaScript code that executes when the UI Policy condition is met (`Execute if true`) or when it’s not met (`Execute if false`).

Key points about UI Policy Scripts:

  • They execute on Desktop/Tablet UI Types by default. You can specify other UI types using the ‘Run scripts in UI type’ field.
  • The `Reverse if false` option on the UI Policy is critical for the `Execute if false` script to run.
  • They are ideal for complex conditional logic that goes beyond simply setting field attributes, or when you need to perform actions based on the condition being true or false, but still want to benefit from the declarative nature of UI Policies.

Troubleshooting Common Issues

When Logic Isn’t Behaving as Expected

This is where understanding the execution order and the specifics of each tool becomes vital.

  • UI Policy Overriding Client Script: If you expect a Client Script to make a field visible but it remains hidden, check if a UI Policy is running afterward and hiding it. Adjust the UI Policy’s order or logic, or move the visibility logic to a UI Policy if it’s a simple attribute change.
  • `onChange` Script Not Firing: Ensure the Field Name on your Client Script is correctly set. Also, verify the script is active and that the UI Type and Global settings are appropriate for your form view. Double-check the `isLoading` and `newValue == ”` conditions.
  • UI Policy Not Triggering: Verify the Condition in your UI Policy is correctly written and that the fields it references are accurate. Ensure the UI Policy is active and configured for the correct table and view. Check the Order field if multiple UI Policies exist for the same table.
  • Conflicting Field States: If a field is sometimes mandatory and sometimes not, or its visibility flickers, it’s often due to multiple Client Scripts or UI Policies interfering with each other. Use the browser’s developer console and the ServiceNow UI Log (available in Rome+ by enabling `glide.ui.debug.script_runs` system property) to trace the execution of your scripts and policies.
  • Scripts Not Running on Mobile or Service Portal: Remember that many Client Scripts and UI Policy Scripts, by default, only run on desktop/tablet UIs. You need to explicitly configure the UI Type for Client Scripts or the Run scripts in UI type field for UI Policy Scripts to ensure they function correctly on mobile or Service Portal views.

Interview Relevance

Understanding the distinction between Client Scripts and UI Policies is a fundamental concept for any ServiceNow developer. In interviews, expect questions like:

  • “When would you choose a UI Policy over a Client Script for making a field read-only?” (Answer: UI Policy Actions for declarative, no-code approach; Client Script if you need to check the old value or perform complex calculations before setting read-only.)
  • “Describe the execution order of Client Scripts and UI Policies.” (Answer: Client Scripts run first, followed by UI Policies. UI Policy logic prevails in conflicts.)
  • “How do you handle form validation before a record is saved?” (Answer: `onSubmit` Client Script for final validation, or UI Policies for attribute control; Data Policies for server-side validation.)
  • “What are the differences between UI Policy Actions and UI Policy Scripts?” (Answer: Actions are for setting mandatory, visible, read-only attributes declaratively; Scripts are for custom JavaScript logic when conditions are met or not met.)
  • “Can you explain the role of `g_form` and `g_user`?” (Answer: `g_form` manipulates form elements; `g_user` retrieves logged-in user information.)
  • “How would you ensure a script runs on both desktop and mobile?” (Answer: Configure the UI Type for Client Scripts or Run scripts in UI type for UI Policy Scripts.)

Being able to articulate the strengths of each, their interaction, and when to employ them will demonstrate a solid grasp of ServiceNow client-side development best practices.

Beyond UI Policies: Introduction to Data Policies

While this article focuses on client-side logic, it’s crucial to briefly mention Data Policies. Data Policies enforce data consistency but operate on the server-side by default. They are similar to UI Policies in that they can set mandatory and read-only attributes, but they apply regardless of how data is entered (form, import sets, web services). You can choose to “Use as UI Policy on client” to have them also behave like UI Policies. Developers cannot apply custom scripts to Data Policies directly; their power lies in enforcing data integrity at the database level.

Conclusion

Both Client Scripts and UI Policies are indispensable tools in the ServiceNow developer’s arsenal for creating interactive and user-friendly forms. By understanding their distinct capabilities, execution order, and when to leverage each, you can build more efficient, maintainable, and robust applications. Remember to consider the complexity of your logic: for simple attribute changes, lean on UI Policies for their declarative simplicity. For custom logic, complex calculations, or actions tied to form submission, Client Scripts offer the power and flexibility of JavaScript. Mastering this distinction will elevate your ServiceNow development skills and lead to better user experiences.


Scroll to Top