Michael Fry1
Kilo Patron

When building efficient forms in ServiceNow, one of the most important techniques is dynamically showing/hiding fields and sections based on user interaction. This not only improves user experience but ensures data integrity by making only the relevant fields visible and required. However, if you are using a combination of client scripts and UI policies, you might experience issues. Issues like tab #1 shows with mandatory fields, but when tab #2 shows, and the first tab should disappear, it does not, and it stays on the form. No fields are mandatory on the first tab, but the end user experience isn’t great.

Let me explain how I solved for this:

Consider the following example script where we want to show a Hold or Cancel section when a field changes to hold or cancel. (You certain could add to this script to show/hide more sections)

function onChange(control, oldValue, newValue, isLoading, isTemplate) {

    g_form.setMandatory('u_on_hold_date', false);

    g_form.setMandatory('u_on_hold_off_date', false);

    g_form.setSectionDisplay('on_hold', false);

 

    g_form.setMandatory('u_reason_for_cancel', false);

    g_form.setMandatory('u_authorized_by', false);

    g_form.setSectionDisplay('cancel', false);

 

    if (newValue == 'hold') {

        g_form.setMandatory('u_on_hold_date', true);

        g_form.setMandatory('u_on_hold_off_date', true);

        g_form.setSectionDisplay('on_hold', true);

 

    } else if (newValue == 'cancel') {

        g_form.setMandatory('u_reason_for_cancel', true);

        g_form.setMandatory('u_authorized_by', true);

        g_form.setSectionDisplay('cancel', true);

    }

 

}

 

The first thing you might notice is that we are not stopping the client script from running onload. Step 1 is to Reset everything: When the field changes, all conditionally mandatory fields are reset to not mandatory, and the associated sections are hidden.

Then If the new value is 'hold':

  • The “on hold” section is shown.
  • Two fields (u_on_hold_date and u_on_hold_off_date) become mandatory.

If the new value is 'cancel':

  • The “cancel” section is displayed.
  • Two different fields (u_reason_for_cancel and u_authorized_by) become mandatory.

Normally we would use UI Policies to set field(s) as mandatory but there's a timing race: the new fields are evaluated as mandatory before the old section (with non-mandatory fields) is hidden, leading to a confusing UI.

Thanks for reading!