Table Methods and Events

Earn 25 points (50 with Pro) in two steps

  1. ① Read through the lesson — each section gets a ✓ as you scroll through it.
  2. ② When every section has a ✓, tap Complete lesson.

0 of 9 read · keep scrolling

✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro

Lesson: Table Methods and Events in AOT

Introduction: Why Table Logic Matters

In the world of application development, particularly within enterprise resource planning (ERP) systems, tables are the foundation of your data architecture. However, a table is rarely just a passive container for rows and columns. To build functional, reliable software, you need a way to enforce business rules, validate data entry, and trigger automated processes at the exact moment a user or system interacts with that data. This is where table methods and events come into play.

Table methods and events provide the hooks necessary to inject custom logic into the database lifecycle. Whether you are validating that a customer’s credit limit is not exceeded, calculating a tax amount automatically when a line item is added, or logging a change in status to an audit table, you rely on these triggers. Understanding how to use these effectively allows you to centralize your business logic. Instead of scattering validation code across hundreds of different user interface forms or external integration services, you place the "source of truth" directly on the table itself.

This lesson explores the mechanics of table methods and the event-driven architecture that modern development frameworks use. We will move beyond basic CRUD (Create, Read, Update, Delete) operations to understand the underlying event pipeline, how to override standard methods, and how to subscribe to events in a way that keeps your system maintainable and upgradeable.


Not read yet

Part 1: The Core Table Methods

When we talk about "methods" on a table, we are referring to the pre-defined functions provided by the framework that govern the data lifecycle. These methods are executed by the kernel or the application runtime whenever a record is created, updated, or deleted.

The Standard Lifecycle Methods

To effectively manage data, you must understand the order in which these methods execute. The standard lifecycle for a record typically follows this path:

  1. initValue(): This method is called when a new record is initialized. It is the perfect place to set default values for fields based on other tables or global settings.
  2. validateField(): This is called whenever an individual field is modified. It allows you to perform field-level validation before the data is committed.
  3. validateWrite(): Before a record is saved to the database, this method runs. It is used to perform cross-field validation, such as checking if a "Start Date" is before an "End Date."
  4. insert(): This runs when the record is physically written to the database. You might use this to generate a unique ID or trigger a secondary action.
  5. update(): Similar to insert(), but triggered when an existing record is modified.
  6. delete(): This is executed when a record is removed from the table. Use this for cleanup tasks or preventing deletion based on business conditions.

Callout: Methods vs. Events It is important to distinguish between overriding a method and subscribing to an event. Overriding a method (using the super() call) allows you to replace or extend the base functionality directly within the class. Subscribing to an event, however, is a non-intrusive way to add logic without modifying the original code. In modern development, event-based programming is preferred because it prevents "code collision" when multiple developers or vendors need to touch the same table.


Not read yet

Part 2: Practical Implementation of Table Methods

Let’s look at how to implement these methods in a real-world scenario. Imagine we have a table called ProjectTask that tracks tasks for a project. We want to ensure that a task cannot be marked as "Completed" if the ActualHours field is zero.

Overriding validateWrite

The validateWrite method returns a boolean. If it returns false, the save operation is aborted, and the user receives an error message.

public boolean validateWrite()
{
    boolean ret;

    // Call the base method to ensure standard validation still runs
    ret = super();

    // Custom business logic
    if (this.Status == TaskStatus::Completed && this.ActualHours == 0)
    {
        error("You cannot complete a task with zero actual hours recorded.");
        ret = false;
    }

    return ret;
}

In this example, we call super() first. This is a critical best practice. If you don't call super(), you bypass all the standard validations (like mandatory field checks or data type constraints) that the framework performs automatically. Always preserve the standard behavior unless you have a very specific reason to suppress it.

Implementing initValue

Setting default values is a common requirement. Suppose every new ProjectTask should default to a status of "Not Started" and set the CreatedDate to today.

public void initValue()
{
    super();

    this.Status = TaskStatus::NotStarted;
    this.CreatedDate = DateTimeUtil::getToday(DateTimeUtil::getUserPreferredTimeZone());
}

This ensures that whenever a user opens a form or an import script creates a new record, the object is pre-populated with the correct initial state.


Not read yet

Part 3: Event-Driven Architecture

While overriding methods is powerful, it can lead to "code bloat" where the table class becomes massive and difficult to maintain. Event handlers allow you to write logic in separate classes. This is known as "CoC" (Chain of Command) or Event Subscription.

Understanding Table Events

Table events are fired by the system automatically. You can subscribe to these events using the [DataEventHandler] attribute. Common table events include:

  • onInserting / onInserted: Before and after a record is written.
  • onUpdating / onUpdated: Before and after a record is updated.
  • onDeleting / onDeleted: Before and after a record is deleted.
  • onValidatingWrite: Allows you to perform validation from an external class.

Example: Using an Event Handler

Let’s say we want to log every time a ProjectTask status changes. Instead of putting this logic inside the update() method of the ProjectTask table, we create a separate class:

class ProjectTaskEventHandler
{
    [DataEventHandler(tableStr(ProjectTask), DataEventType::Updated)]
    public static void ProjectTask_onUpdated(Common sender, DataEventArgs e)
    {
        ProjectTask task = sender as ProjectTask;
        
        if (task.orig().Status != task.Status)
        {
            // Logic to insert a record into an Audit table
            AuditLog::logChange(task.RecId, "Status", task.orig().Status, task.Status);
        }
    }
}

This approach keeps your ProjectTask table class clean. If you ever need to remove the auditing logic, you simply delete or disable the handler class without touching the core table definition.

Tip: Use orig() judiciously When working with the onUpdated event or the update() method, the orig() method is your best friend. It returns the version of the record as it existed before the current changes were applied. This allows you to compare the old value with the new value, which is essential for audit logging or conditional logic that only triggers on specific field changes.


Not read yet

Part 4: Best Practices and Industry Standards

Working with table methods is a high-responsibility task. Because these methods execute every time a record is touched, poorly written code here can have catastrophic performance impacts on the entire system.

1. Keep Methods Lightweight

Table methods are not the place for heavy computations, complex loops, or multiple database lookups. If you need to perform a complex calculation, call a separate service class or a helper function. If you put a slow query inside validateWrite, every single save operation in the system will slow down.

2. Always Handle Errors Gracefully

When validation fails, use the error() or checkFailed() methods. Never use throw unless you want to stop the entire execution stack. Using checkFailed() is particularly useful because it allows the system to collect multiple errors and present them to the user in a single list, rather than stopping at the first error found.

3. Avoid Cross-Table Updates in validate Methods

Never attempt to write data to another table inside a validate method. Validation methods should be "read-only" in nature regarding other tables. If you need to update a related table, do that in the insert() or update() methods (or their corresponding event handlers).

4. Use CoC (Chain of Command) for Extensions

When extending tables in a modular system, always prefer Chain of Command (CoC) over standard event subscriptions where possible. CoC allows you to wrap the next call, providing a cleaner way to manipulate the return values of methods compared to traditional event handlers.


Not read yet

Comparison Table: Methods vs. Events

Feature Overriding Methods Event Handlers
Location Inside the table class External class
Maintainability Lower (Table class gets large) Higher (Modular code)
Execution Directly calls super() Decoupled execution
Use Case Core logic/Standard behavior Auditing, integration, side-effects
Control Can replace entire logic Can only add to logic

Common Pitfalls and How to Avoid Them

Pitfall 1: Infinite Loops

A common mistake is updating a record within the update() method or an onUpdated event handler. If you update the same table you are currently processing, the system will trigger the update logic again, leading to an infinite loop and a system crash.

  • Solution: Always check if the value you are updating has actually changed before applying the update. Alternatively, use a flag or a temporary buffer to ensure the logic only runs once.

Pitfall 2: Bypassing Validation

Some developers use doUpdate() or doInsert() instead of the standard update() and insert() methods because they want to skip validation.

  • Warning: This is a dangerous practice. By using do methods, you bypass all the business logic, audit trails, and data consistency checks built into your system. Only use these methods in extreme migration scenarios where you have full control over the data integrity.

Pitfall 3: Ignoring the "Set-Based" Operations

Most modern ERP systems support "set-based" operations (e.g., update_recordset). These operations are much faster than row-by-row processing, but they do not trigger the update() method.

  • Solution: If you rely on custom logic inside the update() method, be aware that set-based operations will bypass it. You must either disable set-based operations for that table or move your logic to a shared method that is called by both the row-by-row code and the set-based processing logic.

Not read yet

Step-by-Step: Adding a New Validation Rule

If you are tasked with adding a new validation rule to a table, follow this structured workflow to ensure safety and quality.

  1. Analyze the Requirement: Determine if the validation is field-specific or record-wide. If field-specific, use validateField. If record-wide, use validateWrite.
  2. Locate the Table: Find the table in the Application Object Tree (AOT).
  3. Create an Extension: Right-click the table and select "Create extension." Never modify the base table directly if you are working in a layered environment.
  4. Implement the Logic: Use the Chain of Command (CoC) pattern to wrap the existing method.
    • Create a new class with the [ExtensionOf(tableStr(TableName))] attribute.
    • Define the method with the same signature.
    • Add your logic before or after the next call.
  5. Test: Perform unit tests. Create a record that should pass and a record that should fail.
  6. Verify Error Messages: Ensure the user receives a helpful, clear error message that explains exactly what they need to fix.

Code Example: Chain of Command Validation

[ExtensionOf(tableStr(ProjectTask))]
final class ProjectTask_Extension
{
    public boolean validateWrite()
    {
        boolean ret = next validateWrite();

        if (ret && this.TaskPriority == Priority::High && this.Deadline < DateTimeUtil::getToday())
        {
            ret = checkFailed("High priority tasks cannot have a deadline in the past.");
        }

        return ret;
    }
}

This CoC pattern is the industry standard. It is clean, readable, and ensures that the original logic remains intact while your new rule is enforced.


Not read yet

FAQ: Frequently Asked Questions

Q: Can I use validateField for cross-field validation? A: Technically, you can, but it is not recommended. validateField is meant for the specific field being modified. Because the system might not have the values of other fields available or validated yet during that call, it is safer and more reliable to use validateWrite for cross-field logic.

Q: What is the difference between onValidatingWrite and validateWrite? A: validateWrite is the actual method on the table class. onValidatingWrite is an event that occurs within the validateWrite method. Using the event handler is often better for extensions because it allows you to inject logic without needing to override the entire method, though CoC is generally preferred for its ability to modify the return value.

Q: Why does my insert logic not run during data imports? A: Many data import frameworks use "bulk insert" or "set-based" operations to improve performance. As noted earlier, these bypass standard row-level methods. You should check the documentation of your import tool to see how it handles table methods, or consider using a staging table approach where you can run your validation logic before moving the data to the final destination.


Not read yet

Key Takeaways for Developers

  • Lifecycle Awareness: Always know where your code fits in the lifecycle (initValue -> validate -> insert/update -> delete). Misplacing logic is the most common cause of data corruption.
  • The Power of super() and next: Never forget to call the base method. These calls ensure that standard system integrity checks remain active. Skipping them effectively "breaks" the table for the rest of the system.
  • Prefer CoC Over Events: For logic that needs to control the flow (like validation), Chain of Command is superior to event handlers because it allows you to manipulate the return value of the method.
  • Performance First: A table is the heart of your application. If you make the heart beat slowly, the entire body suffers. Keep your table methods lean, fast, and focused.
  • Error Handling: Use checkFailed() to provide a better user experience. It allows for multiple errors to be displayed at once, which is much less frustrating for users than an "error-fix-error-fix" loop.
  • Audit and Log: Use event handlers for non-blocking side effects like audit logging or sending notifications. This keeps your core business logic separate from auxiliary tasks.
  • Avoid the "Do" Methods: Only use doInsert, doUpdate, or doDelete when you have a clear, documented reason to bypass the entire business layer of the application.

By mastering these concepts, you move from being a developer who "writes code" to one who "builds systems." The table methods are the gatekeepers of your data. When you manage them with care, precision, and adherence to these standards, you ensure that your application remains stable, maintainable, and efficient for years to come.

Not read yet

Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.