[X++] find record with Common
When we create a new table we add some useful methods like find
and exist
so the next developer can use these methods to find the a needed record.
When writing generic code and using Commons instead of specific declared tables, there are multiple ways to find a specific record.
Checking if a find
method is present on the table and finding out which parameters it takes is the worst way imho.
For me the best way is to use KeyData.
KeyData is a container that contains the values of the unique fields to search for.
Let me show you an example:
static void findKeyDataExample1(Args _args)
{
Common record;
Map mapKeyData;
KeyData kd;
mapKeyData = new Map(Types::Integer, Types::String);
mapKeyData.insert(fieldNum(SalesTable, SalesId), 'SO-00001');
kd = mapKeyData.pack();
record = SysDictTable::findFromKeyData(tableNum(SalesTable), kd);
}
So this job initializes a new instance of SysDictTable
for the table SalesTable
and makes the common to be the same type. Then it selects the first record and retrieves the KeyData. This will return a map with the FieldCount and the value. The value is then written to a container and passed to the method SysDictTable::findFromKeyData
which returns the same record as we selected first.
This is also working with tables that have more than one field as unique index.
For example PurchAgreementHeader
.
To get KeyData from a record:
static void findKeyDataExample2(Args _args)
{
SalesTable salesTable;
Common recordCheck;
SysDictTable dictTable;
Map mapKeyData;
KeyData kd;
MapEnumerator mapEnum;
select firstOnly salesTable;
mapKeyData = SysDictTable::getKeyData(salesTable);
mapEnum = mapKeyData.getEnumerator();
while (mapEnum.moveNext())
{
info(strFmt('Field ID: %1 Fieldname: %2 Value: %3', mapEnum.currentKey(), fieldId2name(tableNum(salesTable), mapEnum.currentKey()), con2Str(mapEnum.currentValue())));
}
}
Et voilá, we have a few lines of code to select out record in a generic context.