Compare records in code

When saving a record, I had to check which fields had changed and react in a special way if only certain fields (and not any other) changed their value.

I could iterate all fields and compare their values in two table buffers (the original and the updated one), but I thought that D365FO might already have such logic. And indeed it has: in VersioningCompareRecordVersions class. (It exists in AX 2012 too and maybe even in older versions.)

The following example prepares two slightly different records, compares them and shows which fields differ:

// Prepare records to compare
PurchLine origLine;
PurchLine modifiedLine;
 
select firstonly origLine;
modifiedLine.data(origLine);
modifiedLine.PurchQty += 1;
modifiedLine.Name += " updated";
 
// Compare records
var comparer = VersioningCompareRecordVersions::newTableId(tableNum(PurchLine));
container changes = comparer.packChangedFields(VersioningChangeType::Updated, origLine, modifiedLine);
 
// Show modified fields
for (int i = 1; i <= conLen(changes); i++)
{
    container changedField = conpeek(changes, i);
 
    FieldId fieldId = conpeek(changedField, VersioningCompareRecordVersions::posRelatedFieldId());
    info(fieldId2name(tableNum(PurchLine), fieldId));
}

There is more what you can do with VersioningCompareRecordVersions, and there are other related classes as well (such as VersioningComparePurchLine), but this is a good starting point.

Comment List
Related
Recommended