Mastering the GlideForm (g_form) Class in ServiceNow: A Comprehensive Guide






Mastering the GlideForm (g_form) Class: Your ServiceNow Form Manipulation Powerhouse


Mastering the GlideForm (g_form) Class: Your ServiceNow Form Manipulation Powerhouse

In the dynamic world of ServiceNow development, one of the most fundamental and frequently used client-side tools is the GlideForm (g_form) class. If you’ve ever found yourself needing to dynamically alter how a form behaves based on user input, show or hide fields, validate data on the fly, or simply retrieve information from a form, you’ve likely encountered or will soon become intimately familiar with g_form. This article dives deep into the capabilities of the GlideForm class, providing practical insights, real-world examples, and tips for mastering this essential API.

Understanding the GlideForm (g_form) Class

At its core, the GlideForm client-side API is your gateway to interacting with the ServiceNow form from a JavaScript perspective. It provides a rich set of methods that allow you to programmatically control various aspects of a form and its fields directly within the user’s browser. Think of it as the conductor of an orchestra, orchestrating the behavior of form elements in real-time.

The magic happens through the global g_form object. This object is automatically available in all client-side scripts that run in the context of a form – including UI policies, client scripts, and catalog client scripts. It’s crucial to remember that g_form is strictly a client-side API; you cannot access it in server-side scripts.

The syntax is straightforward and intuitive:

g_form.

Let’s explore some of the most common and powerful methods this class offers.

Key GlideForm Methods and Their Practical Applications

The GlideForm API is extensive, but certain methods are the workhorses for everyday form customization. Understanding these will significantly boost your development efficiency.

Retrieving and Setting Field Values

One of the most basic yet critical operations is getting and setting the data within form fields. This is essential for conditional logic, data manipulation, and populating fields based on other selections.

getValue(fieldName)

This method is your go-to for retrieving the current value of a form field. It’s particularly useful when you need to check a field’s content to make decisions about other form elements or trigger subsequent actions.

Practical Example: Displaying a Field’s Value

Imagine you have a ‘Category’ field and a ‘Subcategory’ field on an incident form. You want to display an alert showing the selected ‘Subcategory’ when the ‘Category’ changes. Here’s how you’d do it:

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }

    var selectedSubcategory = g_form.getValue('subcategory');
    alert('The selected Subcategory is: ' + selectedSubcategory);
}

This simple script demonstrates how easily you can access the data entered by the user.

setValue(fieldName, value, displayValue)

Conversely, setValue() allows you to programmatically update a field’s value. The optional `displayValue` parameter is important for fields that have both a stored value (e.g., sys_id) and a display value (e.g., name). If `displayValue` is not provided, ServiceNow will attempt to determine it automatically.

Practical Example: Auto-Populating a Field

Let’s say you want to automatically set the ‘Impact’ and ‘Urgency’ fields based on the ‘Priority’ selected. If ‘Priority’ is set to ‘1 – Critical’, you might want to set ‘Impact’ and ‘Urgency’ to ‘1 – High’.

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }

    if (newValue == '1') { // Assuming '1' is the sys_id for '1 - Critical' priority
        g_form.setValue('impact', '1'); // Assuming '1' is sys_id for '1 - High' impact
        g_form.setValue('urgency', '1'); // Assuming '1' is sys_id for '1 - High' urgency
    } else if (newValue == '2') { // Assuming '2' is for '2 - High' priority
        g_form.setValue('impact', '2'); // Assuming '2' is sys_id for '2 - Medium' impact
        g_form.setValue('urgency', '2'); // Assuming '2' is sys_id for '2 - Medium' urgency
    } else {
        // Reset or set default values for other priorities
        g_form.setValue('impact', '');
        g_form.setValue('urgency', '');
    }
}

This example shows how you can chain together form updates based on a single user selection.

Controlling Field Visibility and Read-Only State

Dynamic form behavior often involves showing or hiding fields, or making them editable or read-only, to guide the user through a process and prevent invalid data entry.

hideField(fieldName, true/false)

This method controls the visibility of a field. Pass true to hide the field and false to show it.

setReadOnly(fieldName, true/false)

This method determines whether a field is editable. Pass true to make it read-only and false to make it editable.

Practical Example: Conditional Field Display and Editability

On a change request form, you might want to show additional fields related to ‘Risk assessment’ only if the ‘Risk’ field is set to ‘High’ or ‘Critical’. Furthermore, you might want to make these fields read-only once they are populated.

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }

    var riskLevel = g_form.getValue('risk');
    var riskAssessmentFields = ['risk_assessment_details', 'risk_mitigation_plan'];

    if (riskLevel == '3' || riskLevel == '4') { // Assuming '3' for High, '4' for Critical
        for (var i = 0; i < riskAssessmentFields.length; i++) {
            g_form.showFieldMsg(riskAssessmentFields[i], '', 'info'); // Clear any previous message
            g_form.showField(riskAssessmentFields[i]);
            g_form.setReadOnly(riskAssessmentFields[i], false); // Make editable initially
        }
    } else {
        for (var i = 0; i < riskAssessmentFields.length; i++) {
            g_form.hideField(riskAssessmentFields[i]);
            g_form.setReadOnly(riskAssessmentFields[i], true); // Make read-only when hidden
        }
    }
}

// Additional logic for making fields read-only after they are filled (e.g., on save)
function onLoad() {
    var riskLevel = g_form.getValue('risk');
    var riskAssessmentFields = ['risk_assessment_details', 'risk_mitigation_plan'];

    if (riskLevel == '3' || riskLevel == '4') {
        for (var i = 0; i < riskAssessmentFields.length; i++) {
            if (g_form.getValue(riskAssessmentFields[i]) != '') {
                g_form.setReadOnly(riskAssessmentFields[i], true);
            }
        }
    }
}

This example shows how to toggle visibility and editability, and also hints at more complex scenarios where you might want to lock down fields after they’ve been completed.

Managing Messages on Forms and Fields

Providing clear feedback to users is paramount for a good user experience. GlideForm offers several methods to display messages.

addInfoMessage(message)

Displays a general informational message at the top of the form, typically in a blue banner.

addErrorMessage(message)

Displays a critical error message, usually in a red banner, at the top of the form. This is often used for form validation.

showFieldMsg(fieldName, message, type)

This method displays a message directly associated with a specific field. The `type` parameter can be ‘info’, ‘warning’, or ‘error’, which dictates the message’s appearance.

clearMessages()

Clears all informational and error messages from the top of the form.

Practical Example: Form Validation and User Guidance

Suppose on a request form, if the ‘Quantity’ is very high, you want to show a warning message next to the ‘Estimated Delivery Date’ field and also a general info message at the top.

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }

    var quantity = parseInt(g_form.getValue('quantity'));
    if (quantity > 1000) {
        g_form.showFieldMsg('estimated_delivery_date', 'Large quantity may affect delivery time. Please confirm.', 'warning');
        g_form.addInfoMessage('A large quantity has been entered. Review delivery estimates.');
    } else {
        g_form.showFieldMsg('estimated_delivery_date', '', 'info'); // Clear the message
        g_form.clearMessages(); // Clear all top messages if no longer needed
    }
}

This allows for targeted feedback to the user.

Manipulating Choice Lists

Choice lists (dropdowns) are a common way to present users with predefined options. GlideForm allows you to dynamically modify these lists.

addOption(fieldName, value, label)

Adds a new option to a choice list. `value` is the internal value stored, and `label` is what the user sees.

removeOption(fieldName, value)

Removes an existing option from a choice list based on its `value`.

clearOptions(fieldName)

Removes all options from a choice list, leaving it empty.

Practical Example: Dynamically Populating a Subcategory List

A classic example is dynamically populating a ‘Subcategory’ dropdown based on the selected ‘Category’.

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }

    var category = g_form.getValue('category');
    g_form.clearOptions('subcategory'); // Clear existing options

    if (category == 'hardware') {
        g_form.addOption('subcategory', 'laptop', 'Laptop');
        g_form.addOption('subcategory', 'desktop', 'Desktop');
        g_form.addOption('subcategory', 'monitor', 'Monitor');
    } else if (category == 'software') {
        g_form.addOption('subcategory', 'os', 'Operating System');
        g_form.addOption('subcategory', 'application', 'Application');
        g_form.addOption('subcategory', 'plugin', 'Plugin');
    } else {
        // Optionally add a default 'none' or 'other' option
        g_form.addOption('subcategory', '', '-- None --');
    }
}

This is incredibly powerful for creating context-aware forms.

Working with Form Sections

Forms can be organized into sections for better usability. GlideForm provides ways to interact with these sections.

getSections()

Returns an array of all section objects on the form.

getSectionName(sectionIndex)

Returns the name of a section at a given index.

Practical Example: Hiding an Entire Section

You might want to hide a ‘Troubleshooting’ section on a ticket form unless the ‘State’ is set to ‘In Progress’ or ‘On Hold’.

function onLoad() {
    var troubleshootingSectionIndex = -1;
    var sections = g_form.getSections();
    for (var i = 0; i < sections.length; i++) {
        if (sections[i].name == 'troubleshooting_section') { // Replace with your actual section name
            troubleshootingSectionIndex = i;
            break;
        }
    }

    if (troubleshootingSectionIndex !== -1) {
        var currentState = g_form.getValue('state');
        if (currentState != '3' && currentState != '4') { // Assuming 3 is In Progress, 4 is On Hold
            g_form.getSections().get(troubleshootingSectionIndex).style.display = 'none';
        }
    }
}

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }

    var troubleshootingSectionIndex = -1;
    var sections = g_form.getSections();
    for (var i = 0; i < sections.length; i++) {
        if (sections[i].name == 'troubleshooting_section') { // Replace with your actual section name
            troubleshootingSectionIndex = i;
            break;
        }
    }

    if (troubleshootingSectionIndex !== -1) {
        var currentState = g_form.getValue('state');
        if (currentState == '3' || currentState == '4') {
            g_form.getSections().get(troubleshootingSectionIndex).style.display = ''; // Show section
        } else {
            g_form.getSections().get(troubleshootingSectionIndex).style.display = 'none'; // Hide section
        }
    }
}

Note: Directly manipulating section styles like this might be less common than using UI Policies for showing/hiding sections, but it demonstrates the underlying capability.

Other Useful GlideForm Methods

Beyond the core functionalities, g_form offers several other methods that can be invaluable:

  • getTableName(): Returns the name of the current table the form belongs to.
  • getDecimalSeparator(): Returns the decimal separator for the current user’s locale.
  • getDigits(): Returns the number of digits to display for decimal numbers.
  • getReference(fieldName, callback): Retrieves the record from a reference field. The callback function receives the retrieved record.
  • isMandatory(fieldName): Checks if a field is mandatory.
  • setMandatory(fieldName, true/false): Sets a field as mandatory or optional.
  • isDisplay(fieldName): Checks if a field is a display field.
  • getDisplayBox(fieldName): Returns the DOM element for a reference field’s display box.
  • getControl(fieldName): Returns the DOM element for a specific form field.
  • render(): Renders the form, forcing a refresh of its elements and states.
  • resetSectionDisplay(resetToDefault): Resets section visibility to their default state.

Troubleshooting Common GlideForm Issues

Even experienced developers encounter hiccups when working with client-side scripts. Here are some common problems and how to address them:

1. g_form is undefined

Symptom: You get a “TypeError: Cannot read properties of undefined (reading ‘getValue’)” or similar error.

Cause: This almost always means your script is running in a context where g_form is not available. This typically happens if you’ve accidentally placed a client script in a server-side execution context (e.g., a Business Rule or Script Include without the proper client-side flag).

Solution: Double-check where your script is running. Ensure it’s a Client Script (UI Policy, Catalog Client Script, or Client Script) and that it’s associated with the correct form or table.

2. Changes are not reflecting on the form

Symptom: You’ve run g_form.setValue() or g_form.showField(), but the form doesn’t update visually.

Cause: Sometimes, the ServiceNow UI needs a nudge to re-render. Also, logic might be flawed, or other scripts could be overwriting your changes.

Solution:

  • Use g_form.render(): After making multiple changes, call g_form.render() to force a form refresh.
  • Check isLoading: In onLoad and onChange client scripts, always check the isLoading parameter. If it’s true, it means the form is still loading, and you should generally avoid making changes that might conflict with the initial load process.
  • Sequence of Scripts: Be mindful of the order in which client scripts and UI policies execute. Complex interactions might require careful ordering.
  • Console Logging: Use gs.log() (in server-side) or console.log() (in client-side scripts) to trace variable values and execution flow. For client scripts, use your browser’s developer console.

3. Reference field issues (getValue returns sys_id, but you want the display value)

Symptom: g_form.getValue('reference_field') returns the sys_id of the record, but you expect the human-readable name.

Cause: getValue(), by default, returns the internal database value (often the sys_id for reference fields). The display value is handled separately by the UI.

Solution:

  • g_form.getDisplayBox('reference_field').value: This can sometimes retrieve the displayed text, but it’s not always reliable and relies on DOM manipulation.
  • g_form.getReference('reference_field', callback): This is the robust way. The `callback` function receives the actual record object, from which you can extract any field, including the display value.

4. Choice list manipulation not working as expected

Symptom: Options are not appearing, disappearing, or appearing with incorrect labels/values.

Cause: Field names might be incorrect, values might clash, or other scripts are interfering.

Solution:

  • Verify Field Names: Ensure the `fieldName` passed to addOption, removeOption, etc., exactly matches the field’s internal name.
  • Clear Options First: If you’re dynamically populating a choice list, it’s almost always best to call g_form.clearOptions(fieldName) before adding new ones to avoid duplicates or stale options.
  • Check Catalog Scripts vs. Client Scripts: For catalog items, catalog client scripts are used. For regular tables, it’s UI Policies or Client Scripts. Ensure you’re using the right type of script.

GlideForm in Interviews: What to Expect

For anyone aiming to work in ServiceNow development, a solid understanding of the GlideForm API is non-negotiable. Interviewers will often probe your knowledge of this class to gauge your practical development skills.

Common Interview Questions Related to GlideForm:

  • “Describe a situation where you used the g_form API to enhance a user’s experience.” (Be ready to walk through a scenario similar to the examples above – conditional visibility, dynamic population, etc.)
  • “What’s the difference between getValue() and getDisplayBox() for a reference field?” (Understand that getValue gets the sys_id, while getDisplayBox interacts with the UI element.)
  • “How would you dynamically add an option to a choice list in a catalog item?” (Expect them to want to hear about addOption(), clearOptions(), and context.)
  • “Explain the role of the isLoading parameter in client scripts.” (This is a critical concept for avoiding race conditions.)
  • “What are the different message types you can display using showFieldMsg() and when would you use them?” (Info, Warning, Error.)
  • “If g_form is undefined, what are the first things you would check?” (Context of execution – client-side vs. server-side.)
  • “How can you make a field read-only based on a condition?” (setReadOnly() and how to trigger it with onChange or UI Policies.)
  • “Describe a complex form validation you implemented using client scripts and g_form.” (This is your chance to show off problem-solving skills with error messages and field visibility.)

Being able to articulate these concepts and provide clear, concise examples will significantly impress an interviewer. Practice explaining these methods in your own words.

Conclusion

The GlideForm (g_form) class is a cornerstone of ServiceNow client-side scripting. It empowers developers to create responsive, dynamic, and user-friendly forms that adapt to specific business needs and user interactions. By mastering its various methods – from simple value retrieval and setting to complex conditional logic and message management – you unlock a powerful toolkit for transforming the standard ServiceNow form experience.

Whether you’re building custom applications, customizing existing modules, or developing on the Service Portal, a deep understanding of g_form will be your greatest asset. So, dive in, experiment with these methods, and become a master of form manipulation in ServiceNow!


Scroll to Top