Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion evaluation/review-fixtures.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,22 @@
"extend-find-entries-navigate-for-new-document-types",
"extend-price-source-type-must-sync-document-subset-enum",
"extend-report-selection-usage-for-new-document-types",
"init-does-not-reset-primary-key-before-reinsert",
"master-data-must-be-inserted-with-trigger",
"new-price-source-must-add-candidate-and-trigger-recalculation",
"only-cascade-derived-field-update-when-not-user-overridden",
"pictures-must-use-media-not-blob",
"report-barcodes-must-use-barcode-module-and-production-font-name",
"round-calculated-unit-prices-to-unit-amount-precision",
"table-design-must-match-bc-table-type-conventions",
"tablerelation-field-length-must-match-related-field",
"transferfields-mirrored-fields-must-match-type-and-length"
]
],
"articleOverrides": {
"only-cascade-derived-field-update-when-not-user-overridden": {
"context": "Target Business Central 29.2, worldwide standard application (w1). The table \"Equipment Model\" and its card page already exist with numbering in place: a No. Series field, its setup and the assignment in OnInsert exist unchanged and are omitted from this file, which shows only what the change touches. The change under review adds only the \"Search Name\" field with its key, the Name OnValidate code that derives it, and the \"Search Name\" field on the card page."
}
}
},
"error-handling": {
"articles": [
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
table 50110 "Sample Order Match"
{
fields
{
field(1; "Entry No."; Integer)
{
AutoIncrement = true;
}
field(2; "Order No."; Code[20])
{
}
field(3; "Order Line No."; Integer)
{
}
field(4; "Matched Qty."; Decimal)
{
}
}

keys
{
key(PK; "Entry No.")
{
Clustered = true;
}
}
}

codeunit 50111 "Sample Order Matcher"
{
procedure MatchAgainstOrderLine(OrderNo: Code[20]; OrderLineNo: Integer; LineQty: Decimal; RequestedQty: Decimal)
var
SampleMatch: Record "Sample Order Match";
AlreadyMatched: Decimal;
QtyToMatch: Decimal;
begin
// Sum what other documents already reserved on this order line.
SampleMatch.SetRange("Order No.", OrderNo);
SampleMatch.SetRange("Order Line No.", OrderLineNo);
if SampleMatch.FindSet() then
repeat
AlreadyMatched += SampleMatch."Matched Qty.";
until SampleMatch.Next() = 0;

QtyToMatch := LineQty - AlreadyMatched;
if QtyToMatch > RequestedQty then
QtyToMatch := RequestedQty;
if QtyToMatch <= 0 then
exit;

// Same variable: Init() keeps "Entry No." from the last row the loop
// read, so once any match exists this Insert fails instead of getting a new number.
SampleMatch.Init();
SampleMatch."Order No." := OrderNo;
SampleMatch."Order Line No." := OrderLineNo;
SampleMatch."Matched Qty." := QtyToMatch;
SampleMatch.Insert(true);
end;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
table 50110 "Sample Order Match"
{
fields
{
field(1; "Entry No."; Integer)
{
AutoIncrement = true;
}
field(2; "Order No."; Code[20])
{
}
field(3; "Order Line No."; Integer)
{
}
field(4; "Matched Qty."; Decimal)
{
}
}

keys
{
key(PK; "Entry No.")
{
Clustered = true;
}
}
}

codeunit 50111 "Sample Order Matcher"
{
procedure MatchAgainstOrderLine(OrderNo: Code[20]; OrderLineNo: Integer; LineQty: Decimal; RequestedQty: Decimal)
var
SampleMatch: Record "Sample Order Match";
ExistingMatch: Record "Sample Order Match";
AlreadyMatched: Decimal;
QtyToMatch: Decimal;
begin
// Sum what other documents already reserved on this order line -
// with a separate variable, so the insert variable never holds a read key.
ExistingMatch.SetRange("Order No.", OrderNo);
ExistingMatch.SetRange("Order Line No.", OrderLineNo);
if ExistingMatch.FindSet() then
repeat
AlreadyMatched += ExistingMatch."Matched Qty.";
until ExistingMatch.Next() = 0;

QtyToMatch := LineQty - AlreadyMatched;
if QtyToMatch > RequestedQty then
QtyToMatch := RequestedQty;
if QtyToMatch <= 0 then
exit;

// SampleMatch has read nothing, so Init() starts from a blank
// "Entry No." and the platform assigns the next number.
SampleMatch.Init();
SampleMatch."Order No." := OrderNo;
SampleMatch."Order Line No." := OrderLineNo;
SampleMatch."Matched Qty." := QtyToMatch;
SampleMatch.Insert(true);
end;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
---
bc-version: [all]
domain: data-modeling
keywords: [init, insert, primary-key, autoincrement, entry-no, record-variable, reuse, findset, transferfields, clear]
technologies: [al]
countries: [w1]
application-area: [all]
---

# `Init()` keeps the primary key: reset it before inserting from a reused record variable

## Description

`Record.Init()` assigns default values to the fields of a record but, per Microsoft Learn, "Primary key and timestamp fields aren't initialized." A record variable that was just used to read (`Get`, `FindSet`/`Next`, `FindLast`), to copy (`TransferFields`), or to `Insert` still holds that record's key after `Init()`. If the code then assigns the other fields and calls `Insert` without assigning a new value to the key field(s) that distinguish the new row, it inserts with the old key, and the insert fails (or, with `if Insert() then;`, silently does nothing).

The case most often missed is an `AutoIncrement` key such as `"Entry No."`, because the code never assigns it on purpose. Learn states that the property assigns numbers automatically and that to insert a record you must "be sure that the value in this field is blank before you insert the record". A value left over from a preceding read is not blank.

The defect does not show while the table, or the filtered set the code reads first, is empty, so tests on fresh data pass. It appears once a matching row exists, or on the second iteration of an insert loop, where the variable holds the number the platform assigned on the first `Insert`.

## Best Practice

Make the key of the inserted row the key you intend, by one of these means:

- Read with one record variable and insert with another, so the insert variable never holds a read key.
- `Clear` the variable before `Init()` when the same variable must be reused.
- Reset an `AutoIncrement` key explicitly after `Init()` or `TransferFields`, as Base Application code does: `EDocMappingLog."Entry No." := 0;` after `TransferFields` in a copy loop in the E-Documents app, and `Rec."Entry No." := 0;` after `Rec.Init()` in the Data Archive app.

Not affected: a variable that has not read, copied or inserted anything since it was declared or cleared; code that assigns a new value to the key field(s) that distinguish each new row between `Init()` and `Insert()` (for example a `"Line No."` counter, while `"Document Type"` and `"Document No."` stay the same); the singleton shape `if not Get() then begin Init(); Insert(); end;`, where the failed `Get` read nothing. Temporary records are not an exception by themselves: `Init()` keeps their key as well, and Learn states that `AutoIncrement` does not work on them, so a temporary insert is clean only when the code assigns a new key before each `Insert`.

See sample: [`init-does-not-reset-primary-key-before-reinsert.good.al`](init-does-not-reset-primary-key-before-reinsert.good.al).

## Anti Pattern

A record variable reads rows (or was just inserted), then `Init()` is called, fields other than the primary key are assigned, and `Insert` follows, with no `Clear`, no separate variable, and no new value for the key field(s) that distinguish the new row. A typical shape sums existing rows in a `FindSet` loop and then creates a new row with the same variable.

See sample: [`init-does-not-reset-primary-key-before-reinsert.bad.al`](init-does-not-reset-primary-key-before-reinsert.bad.al).

## References

- [Learn: Record.Init() method](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/methods-auto/record/record-init-method), Remarks.
- [Learn: AutoIncrement property](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/properties/devenv-autoincrement-property), Remarks.
- [BCApps: E-Documents copy loop resetting `"Entry No."`](https://github.com/microsoft/BCApps/blob/837ef802485ee457e52310d2ecaa08b93d0122fd/src/Apps/W1/EDocument/App/src/Integration/Send/EDocRecurrentBatchSend.Codeunit.al#L79-L84) on an [`AutoIncrement` key](https://github.com/microsoft/BCApps/blob/837ef802485ee457e52310d2ecaa08b93d0122fd/src/Apps/W1/EDocument/App/src/Mapping/EDocMappingLog.Table.al#L17-L21).
- [BCApps: Data Archive `Init()` followed by `"Entry No." := 0`](https://github.com/microsoft/BCApps/blob/837ef802485ee457e52310d2ecaa08b93d0122fd/src/Apps/W1/DataArchive/App/src/DataArchiveMediaField.Table.al#L59-L67) on an [`AutoIncrement` key](https://github.com/microsoft/BCApps/blob/837ef802485ee457e52310d2ecaa08b93d0122fd/src/Apps/W1/DataArchive/App/src/DataArchiveMediaField.Table.al#L24-L29).
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
table 50800 "Equipment Model"
{
fields
{
field(1; "No."; Code[20])
{
DataClassification = CustomerContent;
}
field(2; Name; Text[100])
{
DataClassification = CustomerContent;

trigger OnValidate()
begin
// Overwrites whatever the user typed into "Search Name".
"Search Name" := Name;
end;
}
// Editable: a user can enter an alias, which the next Name change destroys.
field(3; "Search Name"; Code[100])
{
DataClassification = CustomerContent;
ToolTip = 'Specifies an alternate name that you can use to search for the equipment model.';
}
}

keys
{
key(PK; "No.")
{
Clustered = true;
}
key(Search; "Search Name")
{
}
}
}

page 50800 "Equipment Model Card"
{
PageType = Card;
SourceTable = "Equipment Model";

layout
{
area(Content)
{
group(General)
{
field("No."; Rec."No.")
{
}
field(Name; Rec.Name)
{
}
field("Search Name"; Rec."Search Name")
{
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
table 50800 "Equipment Model"
{
fields
{
field(1; "No."; Code[20])
{
DataClassification = CustomerContent;
}
field(2; Name; Text[100])
{
DataClassification = CustomerContent;

trigger OnValidate()
begin
// Recompute only while "Search Name" is blank or still equals the
// transform of the previous Name; any other value is a user override.
if ("Search Name" = UpperCase(xRec.Name)) or ("Search Name" = '') then
"Search Name" := Name;
end;
}
// Editable by design: users may type their own search alias here.
field(3; "Search Name"; Code[100])
{
DataClassification = CustomerContent;
ToolTip = 'Specifies an alternate name that you can use to search for the equipment model.';
}
}

keys
{
key(PK; "No.")
{
Clustered = true;
}
key(Search; "Search Name")
{
}
}
}

page 50800 "Equipment Model Card"
{
PageType = Card;
SourceTable = "Equipment Model";

layout
{
area(Content)
{
group(General)
{
field("No."; Rec."No.")
{
}
field(Name; Rec.Name)
{
}
field("Search Name"; Rec."Search Name")
{
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
---
bc-version: [all]
domain: data-modeling
keywords: [derived-field, search-name, onvalidate, xrec, user-override, cascading-update]
technologies: [al]
countries: [w1]
application-area: [all]
---

# Recompute an editable derived field only while it still holds the derived value

## Description

Some fields are derived from another field by a fixed transform — `"Search Name"` (`Code[100]`) is `Name` (`Text[100]`) as normalized by the `Code` assignment, which converts to uppercase and removes leading and trailing spaces. When the derived field is **editable**, a user may have typed their own value into it. If the source field's `OnValidate` recomputes the derived field unconditionally, the next change to the source (a typo fix in `Name`) silently replaces that value, with no error.

Base Application mainly shows two shapes. Customer, Vendor, Item, Contact, G/L Account, Bank Account, Resource, Project (`Job` table), Fixed Asset and others guard the recompute: `if ("Search Name" = UpperCase(xRec.Name)) or ("Search Name" = '') then "Search Name" := Name;`. Employee also has a blank-only refill in `"Search Name"`'s own `OnValidate` and a change-detecting `UpdateSearchName`. Work Center, Machine Center, Production Order, Routing, Production BOM, Cost Type and others assign unconditionally — Work Center's `"Search Name"` is shown and editable on the Work Center Card, so a value typed there lasts only until `Name` is next validated. Treat that as existing behaviour, not as a template for a field whose user-entered value is meant to persist.

### What `xRec` contributes, and what happens when it has no before-image

Learn describes `xRec` only as "the original values of the record before the changes" and does not state what it holds in a field's `OnValidate` for each code-driven call shape (`Validate(Field, NewValue)`, assign-then-`Validate(Field)`, or a record that was never read). See [`xrec-is-a-before-image-only-in-some-triggers.md`](xrec-is-a-before-image-only-in-some-triggers.md) for triggers where `xRec` is known to mirror `Rec` from code. Do not make correctness depend on it here.

The guard does not need it to. Consider the three states `xRec` can be in here: a true before-image (the guard works as intended); a copy that already holds the new `Name` (the condition reduces to *"`Search Name` is blank or already equals the new transform"*); or a blank/initialized record (the condition reduces to *"`Search Name` is blank"*). In none of them does the guard overwrite a value that differs from both the old and the new transform; its only failure mode is **skipping** the recompute, leaving an unedited `"Search Name"` that still reflects the old `Name`. The blank branch is what still populates a new record's derived field from code, whatever `xRec` holds (Base Application uses the assign-then-validate shape, for example `Item.Description := ...; Item.Validate(Description, Item.Description);` in `CatalogItemManagement.Codeunit.al`). Code that renames existing records in bulk and must also refresh unedited derived values can compare against the stored row (`Get` the record and compare with the transform of the stored `Name`) instead of relying on `xRec`.

## Best Practice

When the derived field is meant to accept user input, recompute it in the source field's `OnValidate` only if it is blank or still equals the transform of the previous source value. Compare using the **same transform you assign** — for a `Code` target that means `UpperCase(xRec.Name)`, not `xRec.Name`, or the guard stops matching as soon as the name contains a lowercase letter. When the derived field is not meant to accept user input, make that explicit with `Editable = false` and recompute unconditionally; the guard would be dead code.

See sample: [`only-cascade-derived-field-update-when-not-user-overridden.good.al`](only-cascade-derived-field-update-when-not-user-overridden.good.al).

## Anti Pattern

A new or changed source-field `OnValidate` copies the source into a derived `Text`/`Code` field (directly, or through `UpperCase`/`CopyStr`/`DelChr`) unconditionally — `"Search Name" := Name;` — while the target is shown as an editable field on a page of the app, so users can type their own value into it. Any value a user entered there is lost the next time the source is validated. Not this anti-pattern: a target declared `Editable = false` or shown on pages only as non-editable; a target the app shows on no page (a pure cache, such as Assembly Header's `"Search Description"`); arithmetic or quantity recomputes; or a guard comparing against a re-read stored value instead of `xRec`.

See sample: [`only-cascade-derived-field-update-when-not-user-overridden.bad.al`](only-cascade-derived-field-update-when-not-user-overridden.bad.al).

## References

- [System-defined variables (`Rec`, `xRec`)](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/devenv-system-defined-variables).
- [BCApps: Customer `Name` `OnValidate` guard and editable `Search Name`](https://github.com/microsoft/BCApps/blob/837ef802485ee457e52310d2ecaa08b93d0122fd/src/Layers/W1/BaseApp/Sales/Customer/Customer.Table.al#L112-L133).
- [BCApps: Vendor `Name` `OnValidate` guard](https://github.com/microsoft/BCApps/blob/837ef802485ee457e52310d2ecaa08b93d0122fd/src/Layers/W1/BaseApp/Purchases/Vendor/Vendor.Table.al#L103-L106).
- [BCApps: Contact `UpdateSearchName` guard](https://github.com/microsoft/BCApps/blob/837ef802485ee457e52310d2ecaa08b93d0122fd/src/Layers/W1/BaseApp/CRM/Contact/Contact.Table.al#L2249-L2250).
- [Learn: Code data type](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/methods-auto/code/code-data-type).
- [BCApps: Item `Description` guard with `CopyStr`](https://github.com/microsoft/BCApps/blob/837ef802485ee457e52310d2ecaa08b93d0122fd/src/Layers/W1/BaseApp/Inventory/Item/Item.Table.al#L108-L111).
- [BCApps: Work Center unconditional recompute](https://github.com/microsoft/BCApps/blob/837ef802485ee457e52310d2ecaa08b93d0122fd/src/Layers/W1/BaseApp/Manufacturing/WorkCenter/WorkCenter.Table.al#L44-L53) and [editable on Work Center Card](https://github.com/microsoft/BCApps/blob/837ef802485ee457e52310d2ecaa08b93d0122fd/src/Layers/W1/BaseApp/Manufacturing/WorkCenter/WorkCenterCard.Page.al#L59-L62).
- [BCApps: assign-then-validate shape on a new item](https://github.com/microsoft/BCApps/blob/837ef802485ee457e52310d2ecaa08b93d0122fd/src/Layers/W1/BaseApp/Inventory/Item/Catalog/CatalogItemManagement.Codeunit.al#L560-L570).
- NAV Design Patterns, "Conditional Cascading Update", originally by Jan Hoek at IDYN ([AL-Dev-Help](https://github.com/BC-Design-Patterns/AL-Dev-Help/blob/d93e2b9166d7f18cfb7533ac32b8d6b40439de62/content/NAVPatterns/1-patterns/conditional-cascading-update/index.md)).
Loading