Triggers overview
This section describes how triggers work in Business Central.
Tip
If you already know the name of, for example, a data type, method, property, or trigger, use the Filter by title field in the upper left corner, above the table of contents to find the topic faster. Otherwise, you can scan the table of contents to find it.
Triggers activate a method when a certain event occurs. When AL methods are run because of a predefined event on either an object or a control, the event triggers the method. Together the event and method make a trigger.
Triggers are useful for doing calculations and validations. Compared to properties, they provide a more diverse, effective way of doing such operations. For example, you can use triggers in reports to control how data is selected and retrieved.
Coding triggers
There are different triggers for the various AL object types. Some triggers are set on the object-level, while others are set on the controls. For example, a table has some triggers on the table object and other triggers on field controls. Or consider reports, which have some triggers on the report object and some on the data items. Trigger are typically added at the end the code block for the object or control. Triggers have the following syntax:
trigger OnWhat()
var
myVariable: type;
begin
// Custom code
end;
Snippet support
Typing the shortcut ttrigger
will create the basic layout for a trigger when using the AL Language extension for Microsoft Dynamics 365 Business Central in Visual Studio Code.
Tip
Use Ctrl+Space to trigger IntelliSense and get assistance on code completion, parameter info, quick info, and member lists. For more information about snippets, see Syntax and snippets.
Example
The following example shows the basic trigger layout for a table object.
table 50100 MyTable
{
fields
{
field(1;MyField; Integer)
{
// Field triggers
trigger OnLookup()
var
myInt: Integer;
begin
end;
}
}
keys
{
key(Key1; MyField)
{
Clustered = true;
}
}
var
myInt: Integer;
// Table object triggers
trigger OnInsert()
begin
end;
trigger OnModify()
begin
end;
trigger OnDelete()
begin
end;
trigger OnRename()
begin
end;
}