Using autoSysFields in ServiceNow: A Comprehensive Guide






Mastering autoSysFields in ServiceNow: A Developer’s Guide to Controlled Updates



Welcome, fellow ServiceNow enthusiast! Ever found yourself needing to perform a bulk update, import historical data, or integrate with an external system in ServiceNow, only to realize that every single record modification automatically triggers a cascade of system field updates and business rules? It’s a common scenario. While ServiceNow’s out-of-the-box automation and auditing capabilities are fantastic for day-to-day operations, there are specific situations where you, the developer, need a bit more control.

This is where two powerful, yet often misunderstood, GlideRecord methods come into play: autoSysFields() and setWorkflow(). In this comprehensive guide, we’ll peel back the layers of these methods, understand their purpose, explore practical use cases, and equip you with the knowledge to wield them responsibly.

The Bedrock: Understanding Glide APIs and GlideRecord

Before we dive into the intricacies of specific methods, let’s quickly recap the foundation upon which much of ServiceNow’s server-side scripting is built: the Glide API, and specifically, GlideRecord.

Glide API Overview: Your Gateway to Platform Interaction

Think of the Glide API as your developer’s toolkit for interacting with the ServiceNow platform. Developers frequently leverage these APIs to extend default application behavior, customize functionalities, and integrate with other systems. Instead of writing complex SQL queries, which you can’t directly do in ServiceNow, Glide APIs allow you to perform database operations and interact with various platform components using intuitive JavaScript classes and methods.

The Glide API is broadly categorized into two main types:

  • Client-Side APIs: These run in the user’s web browser and are used for UI interactions, form manipulation, and user-specific actions. Examples include GlideForm, GlideUser, and GlideAjax.
  • Server-Side APIs: These execute on the ServiceNow instance (the server) and are crucial for database operations, backend logic, and system-level customizations. Key examples include GlideRecord, GlideSystem, and GlideDateTime.

GlideRecord: Your CRUD Superpower

Among the server-side APIs, GlideRecord is undoubtedly the most frequently used and vital. It’s a special JavaScript class, running entirely on the server, designed to perform Create, Read, Update, and Delete (CRUD) operations on ServiceNow tables. Essentially, GlideRecord abstracts away the complexity of direct database interaction, allowing you to manipulate rows and columns using familiar JavaScript syntax.

In essence, if you need to fetch data, create new records, modify existing ones, or delete unwanted entries, GlideRecord is your go-to API. It translates your JavaScript commands into the underlying SQL queries that the database understands, all behind the scenes.

A Crucial Note on Testing: Always, and we mean ALWAYS, test your GlideRecord scripts on a non-production instance first. An improperly constructed query or an erroneous update/delete can lead to significant data loss or corruption, which is a nightmare no one wants to wake up to. Your instances are valuable; treat them with respect!

Here’s a quick recap of GlideRecord’s core characteristics:

  1. Most Common API: Indispensable for server-side scripting.
  2. Server-Side Execution: Runs on the ServiceNow instance, not the browser.
  3. SQL Query Generation: Generates SQL queries implicitly based on your JavaScript.
  4. CRUD Operations: Facilitates all Create, Read, Update, and Delete actions.

The Default Behavior: Auditing and Automation

When you perform a record update using a standard GlideRecord.update() call, ServiceNow does a lot more than just change the field values you explicitly set. It automatically updates several system fields, providing a robust audit trail and triggering various platform automations.

These “system fields” often include:

  • sys_updated_by: The user who performed the last update.
  • sys_updated_on: The date and time of the last update.
  • sys_mod_count: A counter that increments with each modification.
  • sys_created_by: The user who initially created the record.
  • sys_created_on: The date and time of record creation.

In addition to system field updates, a standard update() operation will also trigger any associated:

  • Business Rules: Scripts that run automatically before or after database operations.
  • Workflows: Automated processes that manage tasks and approvals.
  • Flow Designer Flows: Modern, low-code automation sequences.
  • Notifications: Emails or other alerts sent out based on record changes.

For most day-to-day operations, this default behavior is precisely what you want. It ensures data integrity, maintains an accurate history of changes, and automates processes seamlessly. But what if you’re importing historical data from an old system, and you don’t want the sys_updated_on field to show the import date, but rather the original modification date? Or what if you’re doing a mass data cleanup and don’t want to spam users with notifications or trigger complex workflows unnecessarily?

This is where our heroes, autoSysFields() and setWorkflow(), step in.

Taking Control: Introducing autoSysFields()

The autoSysFields() method provides you with the power to tell ServiceNow, “Hey, for this specific update, please don’t touch the standard system audit fields.”

What autoSysFields(false) Does

When you call myGlideRecord.autoSysFields(false); before an update() or insert() operation, you are instructing the system to disable the automatic updates for the following fields for that specific transaction:

  • sys_updated_by
  • sys_updated_on
  • sys_mod_count
  • sys_created_by (for inserts)
  • sys_created_on (for inserts)

This means that if you’re updating a record, its “Last updated by” and “Last updated on” fields will retain their previous values, or you can manually set them to specific historical values if needed. For new records, it allows you to populate sys_created_on and sys_created_by with historical data rather than the current system time and user.

Real-World Scenarios for autoSysFields(false)

“Why would I ever want to bypass auditing?” you might ask. Here are some common and valid scenarios:

  1. Data Migrations & Imports:

    Imagine migrating thousands of incident records from a legacy system. You want the sys_created_on and sys_updated_on fields to reflect the original dates from the source system, not the date of your migration script. Using autoSysFields(false) allows you to set these values manually during the insert/update process, preserving the historical context of the data.

  2. Integrations with External Systems:

    Sometimes an integration might need to synchronize data without altering the ServiceNow record’s internal audit trail. For instance, if an external system is the “source of truth” for modification dates, you might want to ensure ServiceNow reflects those exact dates rather than overwriting them with the integration run date.

  3. Bulk Data Cleanup or Correction:

    Performing a mass update to correct a field value across many records. If these changes are purely technical fixes and shouldn’t impact the “last updated” audit for business reporting, autoSysFields(false) can be useful.

  4. Maintaining Historical Context:

    In specific reporting or compliance scenarios, you might need to ensure that certain record metadata remains unchanged even if a background script modifies other fields.

Code Example: Using autoSysFields(false)

Let’s look at a practical example where we update incident records but explicitly tell ServiceNow not to touch the system fields. This is based on Exercise 43 from the reference material.


var grIncident = new GlideRecord('incident');
grIncident.addQuery('state', 1); // Query for incidents in 'New' state (assuming state 1 is New)
grIncident.query();

gs.info('Attempting to update ' + grIncident.getRowCount() + ' incidents without affecting system fields.');

while (grIncident.next()) {
    // Disable automatic system field updates for this record
    grIncident.autoSysFields(false);

    // Set the new state value
    grIncident.setValue('state', 2); // Set state to 'Active' (assuming state 2 is Active)

    // Perform the update
    grIncident.update();
    gs.info('Updated incident: ' + grIncident.number + ' to state 2, bypassing autoSysFields.');
}
gs.info('Finished updating incidents.');
    

In this example, when an incident’s state is changed from 1 (New) to 2 (Active), the sys_updated_on and sys_updated_by fields of that incident record will *not* be updated to the current time and script user. They will retain their values from the previous update.

Troubleshooting autoSysFields()

  • “My system fields are still updating!”

    Ensure you are calling autoSysFields(false) *before* the update() or insert() call for each record within your loop. If you set it once outside a loop, it won’t apply to subsequent records created or retrieved. Also, double-check that you’re using false as the parameter.

  • “Why are my custom ‘last updated’ fields still being changed by business rules?”

    autoSysFields(false) specifically targets *system* fields (sys_updated_on, etc.). It does *not* prevent business rules or workflows from running, which might then update other fields, including custom “last updated” fields you’ve created. For that, you need its partner: setWorkflow(false).

  • Scoped Application Limitation:

    As mentioned in the reference, autoSysFields() is generally reported to *not work* in scoped applications. If you’re developing within a custom scope, be aware of this limitation. You might need to explore alternative strategies like using import sets with transform maps that allow direct field mapping for system fields, or using a less direct method for specific field overrides if allowed by the API. Always test thoroughly in scoped environments.

Interview Relevance: Why `autoSysFields` Matters

An interviewer asking about autoSysFields() is looking for more than just rote memorization. They want to know if you understand:

  • When to break the rules: Do you recognize scenarios where the default behavior is undesirable?
  • Responsibility: Do you understand the implications of bypassing audit trails?
  • Problem-solving: Can you articulate a solution for common data migration/integration challenges?

Be ready to discuss real-world use cases, the impact on auditing, and why it’s a tool to be used judiciously.

The Silent Partner: Controlling Automation with setWorkflow()

While autoSysFields(false) helps you manage system audit fields, setWorkflow(false) gives you control over the automated processes that typically run when a record is updated or inserted.

What setWorkflow(false) Does

When you call myGlideRecord.setWorkflow(false); before an update() or insert() operation, you are instructing ServiceNow to bypass the execution of:

  • Business Rules: All “before” and “after” business rules configured on that table for that operation will not run.
  • Workflows: No associated workflows will be triggered.
  • Flow Designer Flows: Any flows listening for changes on that table will not execute.
  • Notifications: Email or other notifications based on these changes will not be sent.
  • Rollup Fields/Calculations: Any fields whose values depend on business rules or workflows might not be updated correctly.

This is a powerful method for controlling side effects during bulk operations.

Why Use setWorkflow(false)? Common Scenarios

Disabling workflows and business rules might sound risky, but it’s essential for specific tasks:

  1. Mass Data Imports/Migrations:

    During large-scale data imports, you often want to bring in raw data first and then process it. Triggering a workflow for every single imported record (e.g., a complex approval workflow for 10,000 imported incidents) would be inefficient, potentially create an overwhelming number of tasks, or even lead to performance issues. setWorkflow(false) allows for a “silent” import.

  2. Preventing Infinite Loops:

    In advanced scripting, you might have a script that updates a record, and a business rule on that record then updates *another* record, which in turn could trigger another business rule that updates the *first* record. This can quickly lead to an infinite loop, crashing your instance. setWorkflow(false) is a common defense mechanism to break such potential loops.

  3. Performance Optimization:

    For scripts performing thousands of updates, disabling unnecessary business rules and workflows can significantly improve execution speed, especially if those rules are computationally intensive.

  4. Controlled Data Manipulation:

    Sometimes you just need to change a field value without all the bells and whistles. For example, updating a custom flag on a record for internal processing without sending notifications to users or triggering business logic that isn’t relevant to the flag change.

Code Example: Combining autoSysFields(false) and setWorkflow(false)

It’s very common to use both methods together, especially during data migrations or large-scale updates where you want maximum control. Let’s revisit our incident update example.


var grIncident = new GlideRecord('incident');
grIncident.addQuery('state', 1); // Query for incidents in 'New' state
grIncident.query();

gs.info('Attempting to update ' + grIncident.getRowCount() + ' incidents without affecting system fields AND bypassing workflows/business rules.');

while (grIncident.next()) {
    // Disable automatic system field updates for this record
    grIncident.autoSysFields(false);

    // Disable the execution of business rules, workflows, and notifications for this record
    grIncident.setWorkflow(false);

    // Set the new state value
    grIncident.setValue('state', 2); // Set state to 'Active'

    // Perform the update
    grIncident.update();
    gs.info('Updated incident: ' + grIncident.number + ' to state 2, bypassing autoSysFields and workflow.');
}
gs.info('Finished updating incidents.');
    

With both methods set to false, your script gains unprecedented control over how records are modified, making it ideal for tasks that need to bypass standard platform automation.

Troubleshooting setWorkflow()

  • “My records aren’t behaving as expected after the update!”

    If you use setWorkflow(false), any business rules, client scripts (that run on display/load, not directly impacted by server update), or workflows that *should* have run after the update will be bypassed. This means related tasks might not be created, calculations might not be performed, or notifications might not be sent. This is often the *intended* behavior but can lead to data inconsistencies if not carefully managed. Always consider the full impact.

  • “Why are my records getting stuck in an incorrect state?”

    If a business rule or workflow is responsible for moving a record to its next logical state (e.g., closing child tasks when a parent is closed), disabling them will prevent that progression. You might need to manually script those progressions if you disable workflow.

  • Accidental Disablement:

    Be very careful where you place setWorkflow(false). If it’s accidentally placed in a global business rule or a frequently run script without proper conditional checks, it could cripple vital platform automation.

Interview Relevance: The Double-Edged Sword of `setWorkflow`

Similar to autoSysFields(), understanding setWorkflow() demonstrates a deep grasp of ServiceNow’s execution order and the potential side effects of script actions. Interviewers use this to gauge:

  • Risk awareness: Do you know the dangers of disrupting standard platform automation?
  • Debugging skills: Can you diagnose why a workflow might not be firing after a script update?
  • Best practices: Do you advocate for judicious use and thorough testing?

Be prepared to discuss scenarios where disabling workflow is necessary, but also the potential pitfalls and how you’d mitigate them.

Important Considerations & Best Practices

With great power comes great responsibility, and that certainly applies to autoSysFields() and setWorkflow(). Here are some essential considerations:

1. Use Sparingly and Judiciously

These methods should not be your default approach for every script. In most cases, you want ServiceNow’s built-in auditing and automation to run. Only use autoSysFields(false) and setWorkflow(false) when you have a clear, justified reason to bypass standard platform behavior, such as data migration, integration, or performance-critical bulk operations.

2. Test, Test, Test!

We can’t stress this enough. Changes that bypass business rules and system field updates can have far-reaching and unexpected consequences. Always develop and test your scripts thoroughly in a non-production instance (e.g., a development or sub-production environment) before deploying them to production. Validate data integrity, check for unintended side effects, and ensure your desired outcome is achieved without breaking other functionalities.

3. Document Your Code

When using these methods, make sure to add clear comments to your code explaining *why* you’ve chosen to disable system fields or workflows. This helps future developers (and your future self!) understand the context and intent behind these powerful overrides.

4. Impact on Audit Trails and Reporting

Be mindful that disabling sys_updated_on, sys_updated_by, and sys_mod_count impacts the historical record of changes. This could affect auditing compliance, reporting that relies on these fields, or debugging issues where understanding who made the last change is crucial. Ensure your stakeholders are aware of these implications for data they consume.

5. Performance vs. Integrity

While disabling workflows can offer performance benefits for bulk operations, remember that those workflows often enforce data integrity, create related records, or perform critical calculations. Bypassing them means you might have to manually implement that logic in your script or accept the resulting data inconsistencies. Always weigh the performance gains against potential data integrity risks.

6. Scoped Applications (Revisited)

As noted earlier, autoSysFields() has limitations in scoped applications. This is a critical point for developers building custom apps. Always verify the behavior of these methods within your specific scope and version of ServiceNow. If autoSysFields() truly doesn’t work, you might need to reconsider your approach to historical data population or accept the system field updates. setWorkflow() generally works as expected in scoped apps.

Conclusion: A Developer’s Responsibility

autoSysFields() and setWorkflow() are potent tools in the ServiceNow developer’s arsenal. They offer unparalleled control over how GlideRecord operations interact with the platform’s auditing and automation frameworks. Whether you’re wrangling data from a legacy system, orchestrating complex integrations, or optimizing large-scale updates, these methods empower you to sculpt the platform’s behavior precisely to your needs.

However, with this power comes a significant responsibility. Use them thoughtfully, test meticulously, and document thoroughly. Understanding when and how to deploy these advanced GlideRecord methods effectively is a hallmark of an experienced and highly skilled ServiceNow developer. So go forth, script with confidence, and make your ServiceNow instances work smarter, not harder!


Scroll to Top