MSBA-352 · Lesson 3 of 12 · 20 min

Tables and table extensions

▶ Video coming soon A video version of this lesson is on the way.

Callum came to the second working session with a printed copy of the warranty spreadsheet. It had eleven columns, three of which were always blank, and two different spellings of Bayside Café. "This is what we have," he said. "Tell me what Business Central will store." Noor turned the question to Joss: before writing a single page or line of logic, decide what data the extension owns, what it borrows from standard tables, and what it adds to them.

Owning, borrowing and adding data

Joss sorted the spreadsheet columns into three groups. Some data already lives in Business Central and must not be copied: the customer's name and address belong on the customer card, the item description on the item card, the ship date and serial number on the posted shipment and its item ledger entries. Some data is new and belongs to the extension: a warranty registration for each serial number, with its start and end dates and a status, and a claim log. And some data is a new attribute of a standard record: how long the warranty lasts is a property of each item, so it belongs on the Item table.

Noor added one more check, a habit from functional consulting. Callum's SN-WARRANTY tracking code already has a Warranty Date Formula, and Business Central stores a Warranty Date on item ledger entries when it is used. Why not just use that? Because the formula belongs to the tracking code, not the item, and grinders (24 months) and brewers (12 months) share the same code. A second tracking code would split the setup for no other reason. So the period moved to the item, and the extension stores its own end date. "Always ask what standard already does," Noor said. "Then write down why it is not enough."

A data model. Standard tables Item, Customer, Sales Shipment Header and Item Ledger Entry are shown in grey. A table extension on Item adds CNF Warranty Period. A table extension on Customer adds a FlowField CNF Active Warranties. A new table CNF Warranty Registration has fields Entry No., Serial No., Item No., Customer No., Shipment No., Start Date, End Date and Status, with lines to Item, Customer and Sales Shipment Header. A new table CNF Warranty Claim links to the registration.
The warranty data model: two new tables and two table extensions.

Anatomy of a table object

A table object has a header with an ID, a name and properties, a fields section, a keys section, optional fieldgroups, and triggers. Joss's first table holds one row per registered serial number.

The warranty registration table.
namespace Quarrystone.CorbelFinch.Warranty;

using Microsoft.Inventory.Item;
using Microsoft.Sales.Customer;
using Microsoft.Sales.History;

table 50100 "CNF Warranty Registration"
{
    Caption = 'Warranty Registration';
    DataClassification = CustomerContent;
    LookupPageId = "CNF Warranty Registrations";
    DrillDownPageId = "CNF Warranty Registrations";

    fields
    {
        field(1; "Entry No."; Integer)
        {
            Caption = 'Entry No.';
            AutoIncrement = true;
        }
        field(2; "Serial No."; Code[50])
        {
            Caption = 'Serial No.';
            NotBlank = true;
        }
        field(3; "Item No."; Code[20])
        {
            Caption = 'Item No.';
            TableRelation = Item;
        }
        field(4; "Customer No."; Code[20])
        {
            Caption = 'Customer No.';
            TableRelation = Customer;
        }
        field(5; "Shipment No."; Code[20])
        {
            Caption = 'Shipment No.';
            TableRelation = "Sales Shipment Header";
        }
        field(6; "Start Date"; Date)
        {
            Caption = 'Start Date';
        }
        field(7; "End Date"; Date)
        {
            Caption = 'End Date';
        }
        field(8; Status; Enum "CNF Warranty Status")
        {
            Caption = 'Status';
        }
        field(9; "Customer Name"; Text[100])
        {
            Caption = 'Customer Name';
            FieldClass = FlowField;
            CalcFormula = lookup(Customer.Name where("No." = field("Customer No.")));
            Editable = false;
        }
    }

    keys
    {
        key(PK; "Entry No.") { Clustered = true; }
        key(Serial; "Serial No.", "Item No.") { Unique = true; }
        key(Customer; "Customer No.", "End Date") { }
    }

    fieldgroups
    {
        fieldgroup(DropDown; "Serial No.", "Item No.", "Customer No.", "End Date") { }
    }
}

Joss walked through it with Noor line by line.

Fields. Each field has a number, a name and a data type. Numbers must be unique in the table and should never be reused, because the database identifies fields by number. Code fields hold upper-case identifiers and are the standard type for numbers like item and customer numbers; Text keeps case for names and descriptions. The lengths match the standard fields they refer to: Code[20] for item and customer numbers and Code[50] for serial numbers, the same length Business Central uses on item ledger entries. A mismatch means truncated values or compiler warnings when assigning one to the other.

DataClassification. Every field in a cloud extension needs a data classification, set on the table so all fields inherit it, or on individual fields. The values, such as CustomerContent, EndUserIdentifiableInformation and SystemMetadata, tell Business Central how to treat the data in privacy requests and telemetry. Registrations are the customer's business data, so CustomerContent fits.

TableRelation. A table relation says that a field's value must exist in another table, and it gives users a lookup. Entering an item number that does not exist is rejected, just as on a standard document.

Status. The status field uses an enum, a named list of values defined in its own object. Lesson 9 covers enums; for now it is enough that the values are Active, Expired and Void, and that a new record starts with the first value, Active.

FlowField. Customer Name is not stored. It is a FlowField, calculated from the CalcFormula when a page shows it or when code calls CalcFields. Storing the name would copy it, and the copy would go stale when the customer's name changes, which is exactly the spreadsheet problem Callum wanted to end.

Keys. The first key is the primary key, which must be unique and identifies each row. An automatically incremented entry number is a common choice for log-like tables. The second key enforces a business rule, that a serial number of an item is registered only once, with the Unique property. The third supports a frequent query: all warranties for a customer, sorted by end date. Every key costs a little on every insert, so keys exist for rules and real queries, not "just in case".

LookupPageId and DrillDownPageId. These name the page Business Central opens when a user looks up or drills down into this table from somewhere else. The page arrives in lesson 4. Because it is part of the same project, the compiler resolves the reference when the whole project builds.

Field types at a glance

Common field types.
TypeUse forExample in this app
Code[n]Identifiers; stored upper caseSerial No., Item No.
Text[n]Names, descriptions, notesClaim Description
Integer, BigIntegerCounts and entry numbersEntry No.
DecimalAmounts and quantitiesClaim Cost
Date, Time, DateTimePoints in timeStart Date, End Date
DateFormulaPeriods such as 24M or 1YCNF Warranty Period on Item
BooleanYes or noReturn Required
EnumA fixed or extensible list of valuesStatus
GuidUnique identifiersUsed through the built-in SystemId field
Media, MediaSet, BlobImages and large contentA photo of a damaged part on a claim

Every table also gets system fields automatically: SystemId, a GUID that APIs use as a stable key, plus SystemCreatedAt, SystemCreatedBy, SystemModifiedAt and SystemModifiedBy. Joss did not need to add an audit trail for when a registration was created or changed; the platform already keeps one.

Table triggers and field validation

Tables can run code when records are inserted, modified, deleted or renamed, through the triggers OnInsert, OnModify, OnDelete and OnRename. Each field has an OnValidate trigger that runs when a user enters a value or code calls Validate. Joss used two.

An insert trigger that checks required fields and a validation rule on End Date.
    trigger OnInsert()
    begin
        TestField("Serial No.");
        TestField("Item No.");
        TestField("Customer No.");
    end;

    // inside field(7; "End Date"; Date)
    trigger OnValidate()
    begin
        if ("End Date" <> 0D) and ("End Date" < "Start Date") then
            Error(EndBeforeStartErr, "End Date", "Start Date");
    end;

    var
        EndBeforeStartErr: Label 'The end date %1 cannot be before the start date %2.', Comment = '%1 = end date, %2 = start date';

Triggers run only when the code that inserts or validates asks for them. Insert(true) runs OnInsert; Insert(false) or plain Insert() does not. Assigning a field directly skips OnValidate; calling Validate runs it. That distinction matters in lesson 5, where code creates registrations: Joss had to choose deliberately whether the business rules ran.

Table extensions

The warranty period belongs on the Item table, which Microsoft owns. A tableextension adds fields, keys and triggers to a standard table without changing it. The new fields live in a companion table in the database, but in AL and on pages they behave as if they were part of the item.

Table extensions on Item and Customer. Field numbers come from the app's ID range.
namespace Quarrystone.CorbelFinch.Warranty;

using Microsoft.Inventory.Item;
using Microsoft.Sales.Customer;

tableextension 50100 "CNF Item Warranty" 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;
        }
    }
}

tableextension 50101 "CNF Customer Warranty" extends Customer
{
    fields
    {
        field(50100; "CNF Active Warranties"; Integer)
        {
            Caption = 'Active Warranties';
            FieldClass = FlowField;
            CalcFormula = count("CNF Warranty Registration" where("Customer No." = field("No."), Status = const(Active)));
            Editable = false;
        }
    }
}

Callum would set Warranty Period to 24M on the two grinder items and 12M on the four brewer items and tick Register Warranty on all six. The Boolean is a deliberate switch: not every serial-tracked item should create a registration, and Callum wanted to decide item by item rather than have the code guess from the tracking code.

Table extensions have limits. They can add fields, keys on their own fields, field groups and triggers, and they can change a few properties of existing fields, such as captions. They cannot remove standard fields, change a standard field's type, or change the primary key. A trigger added by a table extension runs after the standard trigger, so it cannot stop Microsoft's code from running; that needs an event, as lesson 6 shows.

Working with records in code

Code reads and writes tables through variables of type Record. A record variable holds one row at a time plus a set of filters that define which rows it can see.

Filtering, counting and looping over records.
procedure CountActiveForItem(ItemNo: Code[20]): Integer
var
    Registration: Record "CNF Warranty Registration";
begin
    Registration.SetRange("Item No.", ItemNo);
    Registration.SetRange(Status, Registration.Status::Active);
    Registration.SetFilter("End Date", '>=%1', Today());
    exit(Registration.Count());
end;

procedure ExpireOverdue()
var
    Registration: Record "CNF Warranty Registration";
begin
    Registration.SetLoadFields(Status, "End Date");
    Registration.SetRange(Status, Registration.Status::Active);
    Registration.SetFilter("End Date", '<%1', Today());
    if Registration.FindSet(true) then
        repeat
            Registration.Status := Registration.Status::Expired;
            Registration.Modify();
        until Registration.Next() = 0;
end;
Record methods Joss used most.
MethodWhat it does
GetReads one record by its primary key
SetRange, SetFilterRestrict the rows a record variable can see
FindFirst, FindLast, FindSetRead the first, last or a set of rows to loop over
NextMoves to the next row in the set; returns 0 at the end
IsEmpty, CountCheck whether rows exist, or how many
Init, Insert, Modify, DeleteCreate, change and remove rows
CalcFieldsCalculate FlowFields for the current row
SetLoadFieldsLoad only the listed fields, which is faster on wide tables

Two habits came from Noor. Use IsEmpty rather than Count when the question is only "are there any", because the database can answer it without counting. And call SetLoadFields before reading large standard tables such as Item Ledger Entry, which has dozens of fields, many of them added by other extensions; loading only the fields the code needs cuts the work for the database.

Temporary tables and setup tables

A record variable declared with the temporary keyword, or a table with TableType set to Temporary, lives only in memory. Nothing is written to the database. Joss would use one in lesson 7 to collect certificate lines before printing.

The extension also needs a few settings, such as how many days after a warranty ends a claim is still accepted. The standard pattern is a setup table with a single row, a primary key field with an empty value, and a card page that shows it. The install codeunit from lesson 2 creates the row.

Worked problem

Choosing where a value lives

Callum asks for four more columns: the café's phone number, the item's warranty period, the date the claim was reported, and the technician who repaired the machine. Where does each belong?

Show solution
  1. Phone number: on the customer card already. Show it on pages through a FlowField or a FactBox, never as a copied field.
  2. Warranty period: an attribute of the item. It is already in the Item table extension as CNF Warranty Period.
  3. Date reported: a fact about a claim. A Date field on the CNF Warranty Claim table.
  4. Technician: also a fact about a claim. A Code[20] field on the claim, related to the standard Resource table, since Corbel & Finch already has resources.

Answer: Reuse standard data, add attributes of standard records through table extensions, and store new facts in the extension's own tables.

FlowFilters and totals

FlowFields can do more than look up a name. A Sum or Count CalcFormula can be filtered by a FlowFilter, a special field that holds a filter rather than a value. The standard Customer table uses a Date Filter FlowFilter so that the Sales field on a customer card shows sales for whatever period the user filters on. Joss used the same idea on the customer table extension: a CNF Claim Date Filter FlowFilter and a CNF Claims in Period FlowField that counts claims reported within the filter. On the customer list, Callum can filter the date to last quarter and see at a glance which cafés had the most claims. Because FlowFields are calculated by the database when shown, they are only fast if a key supports the calculation, so Joss added a key on the claim table by customer and date reported. Noor checked it with the debugger's SQL information, which showed the count running as a single indexed query.

Naming fields for people

Field names in AL are also the default captions and the names other developers search for. Quarrystone's house style follows Microsoft's: words in title case, standard abbreviations such as No. and Qty., and the same name for the same concept everywhere. A field holding an item number is called Item No. in every table, so that a FlowField, a table relation or a report column can be read without checking definitions. Joss's first draft had Item No., ItemNo and Item Number in three tables; the review caught all of them before the first build reached UPDATE-TEST, which mattered, because renaming a field after other code and layouts depend on it is a breaking change in all but name.

Common mistakes

  • MistakeCopying a customer's name into the registration table.

    InsteadStore the customer number and show the name with a FlowField.

  • MistakeMaking a serial number field Code[20] when the standard field is Code[50].

    InsteadMatch the length of the standard field it holds.

  • MistakeLeaving DataClassification at its default in a cloud extension.

    InsteadSet a data classification on the table or every field.

  • MistakeAdding keys for every possible sort order.

    InsteadAdd keys for business rules and real, frequent queries.

  • MistakeAdding Warranty Period to the Item table without an affix.

    InsteadPrefix added fields, as in CNF Warranty Period.

Summary and key terms

  • Decide what data the extension owns, what it borrows and what it adds to standard tables before writing code.
  • A table object has fields, keys, field groups, properties and triggers.
  • FlowFields calculate values from other tables instead of copying them.
  • Table extensions add fields, keys and triggers to standard tables without changing them.
  • Record variables read and write data through filters, finds, loops and insert, modify and delete.
  • Triggers run only when code asks for them with Insert(true), Modify(true) or Validate.
Primary key
The first key of a table, which uniquely identifies each row.
FlowField
A field calculated from a formula over other tables, not stored.
Table relation
A property that limits a field to values that exist in another table.
Table extension
An object that adds fields, keys and triggers to an existing table.
Data classification
A required label describing the privacy category of a field's data.
SetLoadFields
A record method that loads only the named fields for better performance.
Temporary table
A record that exists only in memory and is never written to the database.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Why did Joss put the warranty period on the item rather than use the tracking code's warranty date formula?

    Show answer

    The formula belongs to the tracking code, and grinders and brewers share SN-WARRANTY but have different periods.

  2. What does the Unique property on the Serial key enforce?

    Show answer

    That each serial number of an item can be registered only once.

  3. Code assigns Registration."End Date" directly instead of calling Validate. Does the OnValidate check run?

    Show answer

    No. Direct assignment skips OnValidate; only Validate runs the trigger.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz