Events and Subscribers in Business Central AL: How to Stop Modifying Base Code (C/AL Developer Guide)

In C/AL, customizing Dynamics NAV usually meant one thing: open the standard object and change it. Add a few lines to codeunit 80, tweak a trigger on the Customer table, mark the change with your initials, done.

In Business Central AL, you cannot do that anymore. Base application objects are locked. Your code lives in an extension, and the only way to "hook into" standard logic is through events.

If you are coming from C/AL, this is the single biggest mindset change. This post explains how events work, which types you will use every day, and the mistakes that catch almost every developer in their first month.

Why Events Replaced Code Modifications

Every code modification in NAV created an upgrade problem. When Microsoft shipped a new version, someone had to merge your changes line by line into the new base objects. On a heavily customized database, that could take weeks.

Events fix this by separating two roles:

  • Publisher: the standard code announces "something is happening here" (for example, a sales document is about to be posted).
  • Subscriber: your extension listens for that announcement and runs its own code.

The base code never changes, so upgrades no longer need a merge. Microsoft updates the base app, your extension keeps subscribing, and as long as the event still exists, your code keeps working.

The Three Event Types You Will Actually Use

1. Trigger Events (built in, free on every table and page)

Every table and page in Business Central automatically publishes events around its triggers. You do not need anyone to add them. The most common ones on tables:

  • OnBeforeInsertEvent / OnAfterInsertEvent
  • OnBeforeModifyEvent / OnAfterModifyEvent
  • OnBeforeDeleteEvent / OnAfterDeleteEvent
  • OnBeforeValidateEvent / OnAfterValidateEvent (per field)

This is the direct replacement for writing code inside OnInsert() or OnValidate() in C/SIDE.

2. Integration Events (published by Microsoft or by you)

These are procedures marked with the [IntegrationEvent] attribute, placed at specific points in business logic. Codeunit 80 "Sales-Post", for example, has dozens of them, such as OnBeforePostSalesDoc and OnAfterPostSalesDoc. These are what you use instead of editing posting routines.

3. Business Events

Marked with [BusinessEvent]. They work the same way technically, but they represent a formal, stable contract (for example, "an order was released") that Microsoft promises not to change casually. You will subscribe to these less often than integration events.

Your First Event Subscriber

Requirement: when a user enters a customer's Phone No., strip out spaces and dashes so the data stays clean.

The C/AL way (modify table 18 directly):

Phone No. - OnValidate()
"Phone No." := DELCHR("Phone No.", '=', ' -');  // JB 2010-03-12

The AL way (a subscriber in your own codeunit):

codeunit 50100 "Customer Event Subscribers"
{
    [EventSubscriber(ObjectType::Table, Database::Customer, 'OnAfterValidateEvent', 'Phone No.', false, false)]
    local procedure CleanPhoneNoOnAfterValidate(var Rec: Record Customer)
    begin
        Rec."Phone No." := DelChr(Rec."Phone No.", '=', ' -');
    end;
}

Breaking down the attribute:

  • ObjectType::Table, Database::Customer: which object publishes the event.
  • 'OnAfterValidateEvent': the event name.
  • 'Phone No.': the element name. Only needed for field-level events; leave it as '' otherwise.
  • false, false: SkipOnMissingLicense and SkipOnMissingPermission. Keep both false unless you have a specific reason.

Tip: you do not have to type this by hand. In VS Code, type teventsub and the AL extension gives you a snippet. Even better, open the publisher object, find the event, and use the lightbulb (Ctrl+.) to generate the subscriber with the correct signature.

You Only Need the Parameters You Use

A subscriber does not have to list every parameter of the publisher. It can use any subset, as long as the names and types match exactly. That is why the example above only declares var Rec: Record Customer.

This matters more than it seems. Microsoft sometimes adds parameters to integration events between versions. If your subscriber only declares what it uses, it is far less likely to break on upgrade.

Hooking Into Posting: Integration Events

Requirement: block posting of a sales order if the External Document No. is empty for a specific customer group.

codeunit 50101 "Sales Post Subscribers"
{
    [EventSubscriber(ObjectType::Codeunit, Codeunit::"Sales-Post", 'OnBeforePostSalesDoc', '', false, false)]
    local procedure CheckExtDocNoOnBeforePostSalesDoc(var SalesHeader: Record "Sales Header")
    var
        Customer: Record Customer;
    begin
        if not Customer.Get(SalesHeader."Bill-to Customer No.") then
            exit;

        if Customer."Customer Posting Group" = 'EXPORT' then
            SalesHeader.TestField("External Document No.");
    end;
}

In NAV, this would have been a line inside codeunit 80. Now codeunit 80 stays untouched.

The IsHandled Pattern: Replacing Standard Logic

Sometimes you do not want to add to standard behaviour, you want to replace it. Many Microsoft events include a var IsHandled: Boolean parameter for exactly this. The standard code looks roughly like this:

IsHandled := false;
OnBeforeSomething(Rec, IsHandled);
if IsHandled then
    exit;
// ... standard logic ...

If your subscriber sets IsHandled := true, the standard logic is skipped and yours runs instead.

Use this carefully. If two extensions both subscribe and one sets IsHandled, the other may never get its chance. Also, the order in which subscribers run is not guaranteed. Only use IsHandled when you genuinely need to replace logic, not just to add a check.

Publishing Your Own Events

Good extensions publish events too, so that other developers (or your future self) can extend your code without editing it:

procedure SendLoyaltyPoints(CustomerNo: Code[20]; Points: Integer)
begin
    OnBeforeSendLoyaltyPoints(CustomerNo, Points);
    // ... your logic ...
    OnAfterSendLoyaltyPoints(CustomerNo, Points);
end;

[IntegrationEvent(false, false)]
local procedure OnBeforeSendLoyaltyPoints(CustomerNo: Code[20]; var Points: Integer)
begin
end;

[IntegrationEvent(false, false)]
local procedure OnAfterSendLoyaltyPoints(CustomerNo: Code[20]; Points: Integer)
begin
end;

The publisher procedure has an empty body. That is correct. Its only job is to raise the event.

How to Find the Right Event

This is the question every C/AL developer asks first. Three practical ways:

  1. Event Recorder: search for "Event Recorder" in Business Central, click Start, perform the action in the client (for example, post an order), then click Stop. You get a list of every event raised, and you can copy a ready-made subscriber from it.
  2. Read the base app source: in VS Code, use Go to Definition (F12) on a standard object, then search for OnBefore or OnAfter near the logic you want to change.
  3. Request a new event: if no event exists where you need one, Microsoft accepts event requests through the BCApps / ALAppExtensions repository on GitHub.

Common Mistakes (and How to Avoid Them)

  • Forgetting var on Rec: without var, changes to the record in your subscriber are lost. In the phone number example, the cleaned value would never be saved.
  • Calling Modify inside OnBeforeModifyEvent: this can cause recursion or "record has been changed by another user" errors. Change the fields on Rec and let the standard Modify save them.
  • Ignoring RunTrigger: table trigger events fire even when code calls Insert(false) or Modify(false). Check the RunTrigger parameter if your logic should only run when triggers are executed.
  • Temporary records: trigger events also fire on temporary tables. Add if Rec.IsTemporary then exit; when your logic should only apply to real data.
  • Assuming subscriber order: never write code that depends on running before or after another subscriber.
  • Heavy code in hot events: subscribers on frequently fired events (like OnAfterValidateEvent on Item Journal Line) run on every call. Keep them light, or performance will suffer.

Bonus: Manual Binding

By default, subscribers are always active. If you want a subscriber to run only during a specific process, set the codeunit property EventSubscriberInstance = Manual; and switch it on with BindSubscription():

var
    ImportSubscribers: Codeunit "Import Subscribers";
begin
    BindSubscription(ImportSubscribers);
    RunImport();
    UnbindSubscription(ImportSubscribers);
end;

This is useful for data imports, where you may want to skip validations that make sense for users but slow down bulk loads.

C/AL to AL Quick Reference

In C/AL you would... In AL you use...
Add code to a table's OnInsert Subscriber to OnBeforeInsertEvent or OnAfterInsertEvent
Add code to a field's OnValidate Subscriber to OnAfterValidateEvent with the field name, or a table extension field trigger
Insert lines into codeunit 80 / 90 Subscriber to an integration event in Sales-Post / Purch.-Post
Comment out standard code IsHandled pattern (if the event offers it)
Add a new function others can change later Publish your own [IntegrationEvent]

Wrapping Up

Events feel indirect at first. You write code in one place that runs because of something in another place, and that takes getting used to. But once it clicks, you will not want to go back. No merges, no initials in comments, no upgrade weeks.

Start small: pick one modification from an old NAV database you know well and rewrite it as an event subscriber. That one exercise teaches more than any amount of reading.

For the full reference, see Microsoft's documentation on events in AL.

Comments

Popular posts from this blog

IF - THEN And IF - THEN - ELSE Satement In Microsoft Dynamics NAV

C/AL to AL: The Complete Migration Cheat Sheet (2026 Edition)

10 Most Common AL Compiler Errors in Business Central ( and How to Fix them)