Select Page
Codeunit Triggers Explained in Microsoft Dynamics 365 Business Central (Beginner’s Guide)

May 18, 2026

Introduction

In Microsoft Dynamics 365 Business Central, a Codeunit is an AL object designed to store reusable business logic and process automation.

Codeunits are essential for:

  • Posting routines
  • Batch processing
  • Scheduled automation
  • API integrations
  • Workflow execution
  • Validation services

Unlike tables, codeunits focus on process execution rather than data storage.

What is a Codeunit?

A Codeunit acts as a processing engine where developers centralize logic for:

  • Customer processing
  • Sales posting
  • Purchase workflows
  • Financial transactions
  • Notifications
  • Integration logic

Benefits:

  • Reusable logic
  • Modular design
  • Better maintenance
  • Scalable architecture

Main Codeunit Triggers

1. OnRun()

Overview

OnRun() is the primary execution trigger of a codeunit.

Whenever the codeunit is executed, this trigger runs automatically.

Syntax:

trigger OnRun()
begin
    Message('Codeunit started');
end;

Example:

codeunit 50100 "Customer Processor"
{
    trigger OnRun()
    begin
        Message('Processing customer records...');
    end;
}

Common Uses:

  • Batch posting
  • Data processing
  • Automation jobs
  • Workflow management
  • Scheduled reports

2. OnCheckPreconditions()

Overview

This trigger runs before OnRun() to verify whether setup and conditions are valid.

Syntax:

trigger OnCheckPreconditions()
begin
    if SetupMissing then
        Error('Setup required');
end;

Example:

trigger OnCheckPreconditions()
begin
    if not SalesSetup.Get() then
        Error('Sales setup must be completed first.');
end;

Common Uses:

  • Setup validation
  • Permission checks
  • Configuration verification
  • Security controls
  • Mandatory checks

Best Practices for Codeunits

Keep Logic Modular

Separate code into:

  • Validation procedures
  • Posting procedures
  • Utility functions
  • Integration services

Avoid Heavy UI Logic

Codeunits often run in:

  • Background jobs
  • APIs
  • Job queues

Always Validate Before Execution

Use:

  • Error()
  • TestField()
  • Preconditions

Common Business Scenarios

GoalTrigger
Main process executionOnRun
Validate setupOnCheckPreconditions
Batch automationOnRun
Security checksOnCheckPreconditions

Beginner Mistakes to Avoid

  • Writing all logic in one codeunit
  • Skipping validations
  • Poor modularity
  • Overusing messages
  • Missing security checks

Conclusion

Codeunit triggers are the foundation of reusable business process automation in Business Central.

By mastering:

  • OnRun()
  • OnCheckPreconditions()

Developers can build:

  • Reliable workflows
  • Scalable ERP processes
  • Secure business logic
  • Professional AL solutions

Strong Codeunit design ensures efficient Business Central customization.