MSBA-359 · Lesson 4 of 12 · 22 min
Domain review: AL objects
▶ Video coming soon A video version of this lesson is on the way.
Joss's self-ratings had a hole in the middle of the biggest skill area. He rated tables, page extensions, codeunits and permission sets "can do", because the warranty extension had used them all. He rated Role Centre pages, control add-ins, report substitution, multilanguage reports and query joins "recognize". "That is the shape of a developer who has built one app," Noor said. "The exam was written for someone who has built ten. Let's fill in the other nine, quickly."
Develop objects by using AL is worth 30 to 35 percent of MB-820, the largest area by a wide margin. It has five objective groups: tables and pages, reports, codeunits, entitlement and permission set objects, and queries. This lesson reviews each group, with the emphasis on the bullets developers tend to skip. Events, interfaces and install and upgrade codeunits appear in the codeunits group; lesson 5 covers events and interfaces in depth with the logic area, and lesson 7 covers upgrade code with deployment.
Tables and table extensions
A table defines fields, keys and triggers. A table extension adds fields, keys and trigger code to someone else's table, without changing it. Fields have a class: Normal fields store data, FlowFields calculate a value on demand from other tables using a CalcFormula (Sum, Count, Exist, Lookup, Average, Min or Max), and FlowFilters supply filter values to FlowFields. Every field should carry a DataClassification, such as CustomerContent, EndUserIdentifiableInformation or SystemMetadata, which Business Central uses for privacy tools and which Marketplace validation checks.
Questions on tables often turn on triggers and their order. OnValidate runs when a field is validated, from the page or from code calling Validate. OnInsert, OnModify, OnDelete and OnRename run when the record operation is called with RunTrigger set to true, as Insert(true) does; Insert() or Insert(false) skips the trigger. A table extension can add its own trigger code, which runs alongside the original. The TableType property makes a table Temporary (never stored in the database) or points it at external data, such as Dataverse tables for integration.
tableextension 50100 "CNF Item" extends Item
{
fields
{
field(50100; "CNF Warranty Period"; DateFormula)
{
Caption = 'Warranty Period';
DataClassification = CustomerContent;
}
field(50101; "CNF Register Warranty"; Boolean)
{
Caption = 'Register Warranty';
DataClassification = CustomerContent;
}
}
keys
{
key(CNFWarranty; "CNF Register Warranty") { }
}
}Pages and page extensions
Pages are the user interface. The PageType sets the frame: Card, List, Document, ListPart and CardPart (used inside other pages), Worksheet, StandardDialog, ConfirmationDialog, NavigatePage (wizards), RoleCenter, HeadlinePart, API and PromptDialog (Copilot, lesson 6). A page extension changes someone else's page by placing new fields and actions relative to anchors with addafter, addbefore, addfirst and addlast, by modifying properties of existing controls, and by adding trigger code. It cannot remove a control from the base page; it can hide one with Visible = false.
Actions live in areas. Modern pages place actions in area(Processing), area(Navigation), area(Reporting) and area(Creation), and use the area(Promoted) section with actionref entries to put actions on the action bar. Older code used the Promoted property on each action; the exam expects you to recognize both and to know actionref is the current approach.
Views are saved, named filters and sort orders defined on list pages in AL with a views section, each view setting Filters, OrderBy and, optionally, a SharedLayout. Users switch between them in the filter pane. Views can also be defined in a profile customization for a particular role.
Role Centre pages
A Role Centre is the home page of a role. It has PageType RoleCenter, contains no fields of its own, and is assembled from parts: a HeadlinePart page at the top, cue parts (CardPart pages with cuegroup controls showing tile counts, usually from FlowFields on a cue table), list parts and charts. Its actions are arranged in special areas: area(Sections) for the navigation menu groups, area(Embedding) for links shown in the navigation bar, area(Creation) for "new" actions, and area(Processing) and area(Reporting).
page 50120 "CNF Warranty Clerk RC"
{
PageType = RoleCenter;
Caption = 'Warranty Clerk';
layout
{
area(RoleCenter)
{
part(Headline; "Headline RC Order Processor") { }
part(Cues; "CNF Warranty Cues") { }
part(Claims; "CNF Open Claims Part") { }
}
}
actions
{
area(Sections)
{
group(Warranty)
{
Caption = 'Warranty';
action(Registrations) { RunObject = page "CNF Warranty Registrations"; }
action(Claims) { RunObject = page "CNF Warranty Claims"; }
}
}
area(Creation)
{
action(NewClaim) { Caption = 'New claim'; RunObject = page "CNF Warranty Claim Card"; RunPageMode = Create; }
}
}
}A Role Centre does nothing until a profile uses it. A profile object names the Role Centre and is what users choose in My Settings or what administrators assign. Lesson 5 covers profiles with the other user experience objectives.
Enums and interfaces
An enum is a named list of values stored as integers. Setting Extensible = true lets other apps add values with an enumextension, which is why enums replaced the old Option fields for anything another app might extend. An enum can implement an interface: each value names the codeunit that implements the interface for it, with DefaultImplementation for values that do not specify one and UnknownValueImplementation for values that come from an extension that has since been uninstalled. Calling code then works through the interface without a case statement. In MSBA-352, the Claim Resolution Type enum implemented a CNF Claim Resolution interface, so a future loaner outcome could be added by a separate app.
Control add-ins
A control add-in brings custom HTML, JavaScript and CSS into a page, for a chart, a map or a signature pad that standard controls cannot draw. The controladdin object lists its Scripts, StartupScript and StyleSheets, sizing properties such as RequestedHeight and VerticalStretch, and declares events (raised from JavaScript into AL) and procedures (called from AL into JavaScript). A page hosts it with a usercontrol. In the JavaScript, the add-in raises an AL event with Microsoft.Dynamics.NAV.InvokeExtensibilityMethod. The usual first event is a ready signal: AL must not call the add-in's procedures until the script says it has loaded.
controladdin "CNF Signature Pad"
{
Scripts = 'js/signature.js';
StartupScript = 'js/start.js';
StyleSheets = 'css/signature.css';
RequestedHeight = 220;
VerticalStretch = false;
HorizontalStretch = true;
event ControlReady();
event SignatureCaptured(Base64Png: Text);
procedure Clear();
}Reports
The reports group has eight bullets, more than any other group in this area, and it was Joss's weakest. A report has a dataset of data items (each based on a table) and columns, triggers at report and data item level, an optional request page, and one or more layouts in the rendering section. Layouts can be Word, Excel or RDLC, and DefaultRenderingLayout chooses the default. Users and administrators can add more layouts and choose which to use on the Report Layouts page without code.
Triggers run in a fixed order: OnInitReport, then the request page, then OnPreReport; for each data item OnPreDataItem, then OnAfterGetRecord for every record, then OnPostDataItem; and finally OnPostReport. CurrReport.Skip() skips the current record; CurrReport.Break() ends the current data item; CurrReport.Quit() stops the report. A processing-only report, with ProcessingOnly = true, has no layout and is used to process data in batches, such as a nightly job that expires warranties, with a request page for options.
The request page collects options before the report runs: fields in a layout section, plus the filters on data items that the RequestFilterFields property exposes. SaveValues = true remembers the user's last choices.
Document reports print business documents, such as a warranty certificate or an invoice, usually with a header data item and a line data item linked with DataItemLink, and often run for one record. Which report prints for a given document is set in the Report Selections tables, so a new invoice layout can be chosen by setup rather than code.
Multilanguage reports print in the customer's language, not the user's. The pattern is to set CurrReport.Language (and CurrReport.FormatRegion for number and date formats) in OnAfterGetRecord of the header data item, using the Language codeunit to turn the customer's language code into a language ID. Captions come from the dataset with IncludeCaption or from labels, so they are translated through the app's XLIFF files.
There are two ways to change a report you do not own. A report extension extends a report with new columns, new data items, request page fields, trigger code and new layouts, much as a table extension extends a table. Report substitution replaces the whole report with your own: you subscribe to the OnAfterSubstituteReport event in the ReportManagement codeunit and set the new report ID. Use an extension when you need to add to the existing report, and substitution when you need a different report wherever the original would run.
codeunit 50104 "CNF Report Substitution"
{
[EventSubscriber(ObjectType::Codeunit, Codeunit::ReportManagement, 'OnAfterSubstituteReport', '', false, false)]
local procedure SubstituteShipmentReport(ReportId: Integer; var NewReportId: Integer)
begin
if ReportId = Report::"Standard Sales - Shipment" then
NewReportId := Report::"CNF Shipment With Warranty";
end;
}Codeunits
A codeunit holds procedures. Its Subtype can be Normal, Install, Upgrade, Test or TestRunner. A codeunit with a TableNo receives a record in its OnRun trigger, which is how posting routines are called with Codeunit.Run. Procedures are local (only inside the object), internal (only inside the app), or public by default; lesson 5 covers access modifiers.
Install codeunits run when an extension is first installed, with the OnInstallAppPerCompany and OnInstallAppPerDatabase triggers, and are where default setup records are created. Upgrade codeunits run when a new version replaces an old one, with triggers for checking preconditions, upgrading and validating, each per company and per database. Scheduled tasks run code in the background: the TaskScheduler data type creates a task for a codeunit with an optional failure codeunit and a not-before time, and job queue entries wrap scheduled tasks with recurrence, status and a user interface. Use the job queue when administrators need to see, reschedule or restart the work, which is almost always.
Permission sets and entitlements
A permissionset object grants permissions on objects: for tables, tabledata permissions written as R, I, M and D (read, insert, modify, delete), and X (execute) for other objects. Assignable = true means administrators can assign the set to users and groups; non-assignable sets are building blocks. IncludedPermissionSets composes sets from others, and ExcludedPermissionSets removes the permissions of a set from the composition. A permissionsetextension adds permissions to someone else's set. Lowercase letters grant indirect permission: the user can perform the operation only through code that has direct permission, such as a posting codeunit, not by opening the table.
permissionset 50101 "CNF WARRANTY EDIT"
{
Assignable = true;
Caption = 'Warranty - edit';
IncludedPermissionSets = "CNF WARRANTY VIEW";
Permissions =
tabledata "CNF Warranty Claim" = RIMD,
tabledata "CNF Warranty Registration" = RM,
codeunit "CNF Warranty Mgt." = X;
}Entitlements describe what a licence allows. Microsoft defines them for its own licences, and Marketplace publishers can define entitlement objects that map their offer's plans to permission sets. A user's effective permission is the intersection: what the permission sets grant, limited by what the entitlement allows. Sometimes an object must be usable regardless of the user's permission sets, such as a setup table read by every page of an app, or a page that must open for a user who has no other access. The InherentPermissions property grants permissions on an object to anyone who runs the object, and InherentEntitlements does the same for entitlements. Use them narrowly: they bypass the normal model.
Troubleshooting permissions has standard tools. The Effective Permissions page shows, for a user and an object, what the user has and which sets grant it. The permission recorder on a permission set records what a user's actions touch, to build a set from real use. And the error dialog for a permission failure offers details naming the object and permission missing. In MSBA-352, Dovrin's posting failed on permissions because Joss had tested only as a super user; the fix was an indirect permission in the POST set, and the lesson was to test as a user with only the intended sets.
Queries
A query object retrieves data from one or more tables in a single SQL statement. It has dataitems (one per table), nested to show how they link with DataItemLink, and the SqlJoinType property on the inner data item sets the join: LeftOuterJoin (the default), InnerJoin, RightOuterJoin, FullOuterJoin or CrossJoin. Columns select fields; a column with a Method of Sum, Count, Average, Min or Max aggregates, and the other columns become the grouping. Filter elements and DataItemTableFilter limit rows; ColumnFilter filters on a column, including on aggregated values. OrderBy sorts and TopNumberOfRows limits.
query 50100 "CNF Claims by Item Month"
{
QueryType = Normal;
DataAccessIntent = ReadOnly;
elements
{
dataitem(Claim; "CNF Warranty Claim")
{
column(ItemNo; "Item No.") { }
column(ClaimYear; "Claim Date") { Method = Year; }
column(ClaimMonth; "Claim Date") { Method = Month; }
column(Claims; "Entry No.") { Method = Count; }
dataitem(Item; Item)
{
DataItemLink = "No." = Claim."Item No.";
SqlJoinType = InnerJoin;
column(ItemCategory; "Item Category Code") { }
}
}
}
}Code uses a query through a variable: set filters, call Open, loop with Read to get each row, and Close. That is also how the outline's bullet "use a query to create a report" works: a report with an Integer data item, or a temporary buffer, reads rows from the query in its triggers and passes them to the layout, giving the report the speed of one aggregated SQL statement instead of nested loops. A query with QueryType = API is exposed as a read-only API endpoint, which lesson 6 revisits.
XMLports: read, don't study
XMLports, which import and export XML and text files, are no longer in the outline. They still exist in AL, and much older code uses them for file imports. If an exam scenario mentions file import today, the modern answers are usually streams with CSV buffer or JSON handling, an Excel import through the Excel Buffer table, configuration packages for data migration, or an API. Recognize an XMLport if you see one in a code listing; do not spend study hours on its properties.
Worked problem
Choosing the object
Five requirements arrive at once: (1) add a "Grind" field to sales lines; (2) show monthly totals of grinder claims by category quickly; (3) print warranty certificates in the customer's language; (4) let clerks start their day from a dedicated home page; (5) let a future app add a new claim outcome without changing this app.
Show solution
- (1) A table extension on Sales Line and a page extension on the sales order subform.
- (2) A query with an inner join to Item and a Count method, with read-only data access intent.
- (3) A document report that sets CurrReport.Language from the customer's language code in the header's OnAfterGetRecord, with translated captions.
- (4) A Role Centre page used by a profile.
- (5) An extensible enum that implements an interface.
Answer: Each requirement maps to one object type. Most AL objects questions are recognition of which object, property or trigger fits a requirement.
Common mistakes
MistakeExpecting Insert() to run the OnInsert trigger.
InsteadInsert(true) runs it; Insert() and Insert(false) do not.
MistakeUsing a report extension to replace a report everywhere it runs.
InsteadUse report substitution through OnAfterSubstituteReport.
MistakeSetting the report language from the user's settings for customer documents.
InsteadSet CurrReport.Language from the customer's language code.
MistakeGranting broad permission sets to make a setup table readable.
InsteadConsider InherentPermissions on the object, used narrowly.
MistakeLooping with CalcFields to total data for a report.
InsteadUse a query with aggregate methods.
Summary and key terms
- Table fields are Normal, FlowField or FlowFilter; every field needs a DataClassification.
- Page extensions place controls with anchors and can hide but not remove base controls; actionref puts actions on the action bar.
- Role Centres are built from parts and used through profiles; control add-ins bring HTML and JavaScript into pages.
- Reports: dataset, triggers, request page and Word, Excel or RDLC layouts; extend with report extensions, replace with substitution.
- Permission sets use RIMDX, indirect permissions and composition; entitlements cap them; InherentPermissions grants on the object itself.
- Queries join and aggregate in one SQL statement and can feed reports or APIs.
- FlowField
- A calculated field whose value comes from a CalcFormula over other tables.
- Report extension
- An object that adds columns, data items, request page fields and layouts to an existing report.
- Report substitution
- Replacing one report with another by subscribing to OnAfterSubstituteReport.
- Control add-in
- An object that hosts custom HTML, JavaScript and CSS inside a page.
- Indirect permission
- Permission to use a table only through code that has direct permission.
- InherentPermissions
- An object property granting permissions on the object to anyone running it.
- SqlJoinType
- The query property that sets how a data item joins its parent.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Which property makes a report run without a layout?
Show answer
ProcessingOnly = true.
What does a lowercase m mean in a permission set?
Show answer
Indirect modify permission.
Which default implementation handles enum values from an uninstalled app?
Show answer
UnknownValueImplementation.
Which query property sets an inner join?
Show answer
SqlJoinType = InnerJoin on the inner data item.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.