Client-Side UI Actions: A Comprehensive Guide Explained






Client-Side UI Actions Explained: Mastering Form Behavior in ServiceNow


Client-Side UI Actions Explained: Mastering Form Behavior in ServiceNow

In the world of ServiceNow, user experience is paramount. A well-designed form that guides users, enforces data integrity, and provides relevant information at the right time can significantly boost productivity and reduce errors. Much of this dynamic form behavior is orchestrated on the client-side, primarily through UI Policies. This article dives deep into how client-side UI actions, with a special focus on UI Policies, work their magic, making your ServiceNow forms intelligent and responsive.

We’ll explore what UI Policies are, how they differ from other form manipulation techniques, and how to leverage their various components to create sophisticated user interfaces. We’ll also touch upon related concepts like Data Policies, Reference Qualifiers, and Dependent/Calculated Values, providing a holistic view of form customization in ServiceNow.

Understanding the Core: What are UI Policies?

At its heart, a UI Policy is a set of conditions and actions designed to dynamically change the behavior of fields on a ServiceNow form. Think of it as a set of rules that say, “If this happens, then do that.” These rules operate directly in the user’s browser (the client-side), meaning the form can react instantly to user input without needing to communicate back to the server for every small change. This results in a snappier, more intuitive user experience.

UI Policies are incredibly versatile. They can be used to:

  • Make fields mandatory (required).
  • Make fields read-only (prevent users from editing).
  • Make fields visible or hidden.
  • Set a field’s default value.
  • Execute scripts for more complex logic.

This stands in contrast to other methods like Client Scripts, which are also client-side but are purely script-based. UI Policies offer a more declarative, condition-driven approach, often making them easier to build and maintain for common form manipulations.

The Power of Declarative Control: UI Policies vs. Scripting

While both UI Policies and Client Scripts can achieve similar outcomes, their approach differs:

  • UI Policies: Focus on conditions and actions. You define what should happen based on specific field values or states. This is great for straightforward requirements like “if the incident state is ‘Resolved’, make the ‘Resolution notes’ field mandatory.”
  • Client Scripts: Are purely code-driven. They offer ultimate flexibility for complex logic, calculations, and interactions that go beyond simple condition-action pairs. However, they require more coding expertise and can be harder to maintain if not well-documented.

It’s common to use both. UI Policies handle the bulk of standard form behavior, while Client Scripts can be invoked from UI Policies (or run independently) for more intricate scenarios.

Key Components of a UI Policy

When you create a UI Policy, you’re essentially defining a set of rules. These rules are broken down into the UI Policy itself and its associated UI Policy Actions.

The UI Policy Record

The main UI Policy record is where you define the overarching settings for your policy. Key fields include:

  • Short description: A clear, concise name for your policy (e.g., “Make Assignment Group mandatory for Incident”).
  • Table: The table to which this UI Policy applies (e.g., Incident, Change Request).
  • Order: Determines the order in which UI Policies are executed if multiple apply to the same form. Lower numbers run first.
  • Condition: This is the core logic. It defines when the UI Policy should be evaluated. You can use simple field comparisons (e.g., State is Resolved) or more complex script conditions.
  • Active: Ensures the policy is enabled.
  • Run scripts: (Interview Relevance: A common question in interviews is whether scripting is possible within UI Policies. This checkbox is the key!) If checked, it allows you to execute client-side scripts within the UI Policy. This is crucial for advanced logic.
  • On Load: (Reference: Q61) When checked, the UI Policy’s conditions and actions are evaluated as soon as the form loads. If unchecked, the policy’s actions only trigger when a field value that is part of the condition changes. This is vital for immediate form responsiveness.
  • Reverse if false: (Reference: Q60) This is a powerful setting. If checked, when the UI Policy’s condition evaluates to false, the actions are reversed. For example, if a field is made mandatory by the policy when the condition is true, it will become optional again when the condition is false. This is excellent for creating dynamic visibility and mandatory requirements.
  • Inherit: (Reference: Q62) When checked, the UI Policy will also apply to child tables that extend the table on which the UI Policy is defined. This is a fantastic way to promote consistency across related tables.
  • Global: (Reference: Q59) If checked, the UI Policy applies to all views of the table. If unchecked, you can specify a particular view where the UI Policy should operate.

UI Policy Actions

Within each UI Policy, you define one or more UI Policy Actions. These are the specific “do this” parts of your rules. Each action targets a particular field and specifies what to do with it.

  • Field: The target field on the form (e.g., `short_description`, `assignment_group`).
  • Visible: Whether the field should be visible.
  • Mandatory: Whether the field should be mandatory.
  • Read only: Whether the field should be read-only.
  • Set to default value: Allows you to set a default value for the field.
  • Field style: Apply inline CSS styling to the field.

Troubleshooting Tip: If your UI Policy actions aren’t working as expected, first check the UI Policy’s overall condition. If the condition isn’t met, no actions will be executed. Also, ensure the UI Policy Action targets the correct field name.

Practical Examples and Scenarios

Scenario 1: Making Fields Mandatory Based on State

Let’s say for Incidents, when the State is changed to “Resolved” or “Closed,” we want to make the “Work notes” and “Resolution notes” fields mandatory. Otherwise, they should be optional.

  1. Create a new UI Policy on the incident table.
  2. Short description: “Mandatory fields for Resolved/Closed Incidents”
  3. Condition: State is Resolved OR State is Closed
  4. Reverse if false: Check this box.
  5. On Load: Check this box (so it applies immediately when the form loads and also reacts to changes).
  6. Create two UI Policy Actions:
    • Field: Work notes, Mandatory: True
    • Field: Resolution notes, Mandatory: True

With Reverse if false checked, when the state is *not* Resolved or Closed, these fields will automatically become optional again.

Scenario 2: Hiding Fields for Specific Users

Perhaps you want to hide the “Close notes” field for agents who are not part of the “IT Support” assignment group.

This is where UI Policies alone might become complex if you need to check group membership dynamically within the UI Policy condition. A common approach here would be to leverage the Run scripts option.

  1. Create a new UI Policy on the incident table.
  2. Short description: “Hide Close Notes for Non-IT Support”
  3. Condition: Leave this blank for now, or set a broad condition like true. The script will handle the logic.
  4. Reverse if false: Check this box.
  5. On Load: Check this box.
  6. Run scripts: Check this box.
  7. Create one UI Policy Action:
    • Field: Close notes, Visible: True (initially)
  8. In the “UI Policy Script” section (which appears when Run scripts is checked), you would write JavaScript. You’d likely have a “Script” field for when the condition is true and an “Else If Condition” script or “Else Script” for when it’s false.

The script might look something like this (simplified):


    // This script would execute when the UI Policy condition is met (or always if condition is true)
    // And 'Reverse if false' is used to toggle visibility

    var currentUser = g_user.getUserID(); // Get current user's sys_id (Reference: Q13)
    var isITSupport = false;

    // For server-side group check, you'd typically use a GlideAjax call from client script
    // or have a server-side script include that returns the boolean.
    // For demonstration, let's assume a hypothetical client-side check or a server-side result.

    // A more realistic client-side approach would involve a GlideAjax call to a Script Include
    // to check group membership on the server.

    // For illustrative purposes within a UI Policy script (less common for group checks):
    // You might have a helper script include that returns true/false for group membership.
    // Let's pretend we have a function 'isUserInGroup(userId, groupName)' available.
    // If you have a custom global function:
    // if (isUserInGroup(currentUser, 'IT Support')) {
    //     isITSupport = true;
    // }

    // **More realistic example using server-side gs.getUser().isMemberOf() via a Script Include**
    // This UI Policy script would then call that Script Include.
    // Example Client Script Snippet (called from UI Policy script):
    /*
    var ga = new GlideAjax('MyUserUtils'); // Script Include name
    ga.addParam('sysparm_name', 'isMemberOf');
    ga.addParam('sysparm_group_name', 'IT Support');
    ga.getXML(function(response) {
        var result = response.responseXML.documentElement.getAttribute("answer");
        if (result == 'true') {
            g_form.setVisible('close_notes', false); // Hide the field
        } else {
            g_form.setVisible('close_notes', true); // Show the field
        }
    });
    */

    // ***NOTE: Direct server-side gs.getUser().isMemberOf() is NOT available client-side directly***
    // Reference: Q15 shows gs.getUser().isMemberOf() is server-side.
    // The correct way is to use GlideAjax to call a Script Include that performs the server-side check.

    // For the sake of this explanation focusing on UI Policy structure:
    // Let's assume a scenario where the condition is simply met by the policy.
    // If the condition of the UI Policy were: 'assignment_group.name = IT Support'
    // Then the action would be: Make 'close_notes' Visible: false

    // When 'Reverse if False' is unchecked, and Run Scripts is checked:
    // In the UI Policy Action, you would set Visible to False.
    // In the UI Policy Script, you might have logic to set it back to True.

    // **Let's simplify the example for UI Policy Action focus:**
    // UI Policy Condition: State is Resolved
    // UI Policy Action: Field: Close notes, Visible: False
    // UI Policy Action: Field: Work notes, Mandatory: True
    // Reverse if False: Checked
    // This means 'Close notes' is visible by default, becomes hidden when State is Resolved.
    // And 'Work notes' is optional by default, becomes mandatory when State is Resolved.
    

Troubleshooting Tip: If your scripts within UI Policies aren’t running, ensure “Run scripts” is checked on the UI Policy record. Also, check the browser’s JavaScript console for any errors. Make sure you’re using the correct API calls (e.g., g_form.setVisible(), g_form.setMandatory()).

Beyond UI Policies: Related Concepts

Mandatory, Read-Only, and Display Fields

As mentioned, UI Policies are a primary way to control these aspects. However, you can also achieve this through:

  • Dictionary Properties: The base definition of a field in the Dictionary (e.g., making a field mandatory by default for all records).
  • Dictionary Overrides: Modifying a field’s definition for a specific table.
  • Data Policies: (Reference: Q66) These are similar to UI Policies but operate on both client and server sides, ensuring data integrity regardless of how the data is entered (e.g., form, import, API).
  • g_form.setMandatory(Script): This is a client-side JavaScript API call, typically used within Client Scripts or UI Policy Scripts. (Reference: Q42)

Interview Relevance: Be prepared to explain the differences between UI Policies and Data Policies and when to use each. UI Policies are for form presentation and user interaction, while Data Policies are for data integrity across all data sources.

Attributes

Attributes are special keywords added to a field’s definition in the Dictionary or Dictionary Overrides that alter its behavior or appearance. (Reference: Q51)

Examples include:

  • no_email: Prevents emails from being sent for changes to this field.
  • no_attachment: (Reference: Q53) Disables attachments for records where this field is prominent, or on the form itself. You’d typically add this to the attachment field on a form or to the collection field.
  • tree_picker: Changes how a reference field is displayed, using a hierarchical tree view.

Attributes provide a declarative way to apply specific behaviors without scripting.

Reference Qualifiers

Reference fields allow users to select records from another table. Reference Qualifiers are used to restrict the choices available in these reference fields, making them more relevant. (Reference: Q48)

There are three types:

  1. Simple: Uses basic query conditions (e.g., `active=true`). You can filter for active users in a ‘User’ reference field.
  2. Dynamic: Uses pre-defined “Dynamic Filter Options” that can adapt based on form context (e.g., showing only incidents assigned to the current user’s group).
  3. Advanced: Uses JavaScript to define complex filtering logic, offering the most flexibility. You can use client-side APIs within these scripts.

Difference between types:

  • Simple vs. Dynamic: Simple is static; Dynamic can change based on other form fields.
  • Dynamic vs. Advanced: Dynamic uses a dropdown selection of pre-configured options; Advanced lets you write custom JavaScript for maximum control.
  • Simple vs. Advanced: Simple is for basic field=value queries; Advanced is for complex scripting logic.

Example (Advanced): For a reference field to the ‘Incident’ table, you might use an Advanced Reference Qualifier like: javascript: 'assigned_to=' + g_user.userID + '^priority=1'. This would show only incidents assigned to the currently logged-in user with priority 1.

Dependent Values

Dependent Values create cascaded dropdowns. The choices in one field (the dependent field) change based on the selection in another field (the parent field). (Reference: Q49)

Example: A common scenario is ‘Category’ and ‘Subcategory’ on the Incident table. If you select ‘Hardware’ as the Category, the Subcategory dropdown might show ‘Laptop’, ‘Desktop’, ‘Printer’. If you select ‘Software’, it might show ‘Application’, ‘OS’. This is configured in the dictionary entry of the dependent field, linking it to the parent.

Calculated Values

A Calculated Value allows a field’s value to be automatically computed based on other fields using server-side logic. (Reference: Q50)

Example: You could have a ‘Total Cost’ field that is calculated by summing ‘Quantity’ and ‘Unit Price’. This is configured in the Dictionary entry for ‘Total Cost’ using the ‘Calculation’ attribute, pointing to a script that performs the sum.

Note: While calculated values are often server-side, client scripts can also perform calculations and update fields, providing a similar outcome dynamically on the form.

Troubleshooting Common UI Policy Issues

  • UI Policy not firing:
    • Check if the UI Policy is Active.
    • Verify the Condition is correct and the fields involved are accessible.
    • Ensure On Load is checked if you expect immediate behavior.
    • If using Reverse if False, make sure the condition is correctly evaluating to both true and false states.
    • Check the Order of UI Policies; a lower-ordered policy might be overriding another.
  • UI Policy Actions not working:
    • Double-check the target Field name in the UI Policy Action.
    • Ensure the action (e.g., Mandatory, Visible) is set correctly.
    • If Run scripts is checked, inspect the script for syntax errors or logical flaws in the browser’s developer console.
    • For visibility issues, ensure the field is not hidden by other means (e.g., form layout, another UI Policy, or security roles).
  • Performance issues:
    • Too many complex UI Policies, especially those with extensive scripting or running on load for many records, can slow down form loading.
    • Optimize conditions.
    • Avoid unnecessary scripting.
    • Use Data Policies for server-side integrity checks to offload client-side processing.
    • Consider disabling Run scripts if the actions can be achieved declaratively.

Interview Relevance: What to Emphasize

When discussing UI Policies in an interview, highlight:

  • Their purpose: Enhancing user experience and data integrity on the client-side.
  • The difference between UI Policies and Client Scripts (declarative vs. scripting).
  • The importance of On Load and Reverse if False.
  • The role of Run scripts and when to use it.
  • How UI Policies interact with other form customization features like Dictionary Attributes, Reference Qualifiers, and Dependent Values.
  • The distinction between UI Policies and Data Policies.
  • Ability to troubleshoot common issues.

You might be asked to explain scenarios like: “How would you make a field mandatory only when a specific checkbox is checked?” or “How would you hide a field based on the user’s role?” Being able to articulate the UI Policy approach (or when a Client Script might be better) is key.

Conclusion

Client-side UI Actions, particularly UI Policies, are fundamental tools for building intelligent and user-friendly ServiceNow forms. By mastering their components—conditions, actions, scripting, and advanced settings like ‘Reverse if False’—you can create dynamic experiences that guide users, enforce business rules, and significantly improve data quality. Understanding how UI Policies integrate with other form customization features provides a comprehensive skillset for any ServiceNow developer or administrator.

Remember, the goal is always to create a seamless and efficient experience for your end-users. UI Policies are your allies in achieving that.


Scroll to Top