PeopleCode | Create an object reference by using dynamic naming
A. First Name Basis
A typical page object, such as a record or field, is referred to directly via its object name:
&taxRate01 = &taxRec.TAX_RATE_01.Value; &taxRate02 = &taxRec.TAX_RATE_02.Value; &taxRate03 = &taxRec.TAX_RATE_03.Value;
But what if you’re faced with a requirement where the field name is not known with certainly in advance? Consider the following example. The tax rate value depends on the value of the gross amount field: tax rate 01 is used for amounts of 100 or less, tax rate 02 is for amounts between 100 and 500, and tax rate 03 is for amounts over 500. Is there any way to refer to the field name dynamically?
B. Dynamic Field Naming
Here is some code to handle this requirement, using dynamic field naming:
Local number &grossAmount, &taxAmount; Local string &taxRate; Local Record &taxRec; /* Set tax rate depending on gross amount */ Evaluate &grossAmount When <= 100 &taxRate = "01"; Break; When <= 500 &taxRate = "02"; Break; When-Other &taxRate = "03"; Break; End-Evaluate; /* Calculate tax */ &taxAmount = &grossAmount * &taxRec.GetField(@("Field.TAX_RATE_" | &taxRate)).Value;
The construct to take special note of here is part of the final line:
&taxRec.GetField(@("Field.TAX_RATE_" | &taxRate)).Value;
Instead of referring to the TAX_RATE_XX field directly, the PeopleCode instead creates the field name dynamically. This is done by taking the string ‘TAX_RATE_’ and then appending the two digit tax rate set by the ‘Evaluate’ statement. To clarify to the system that this is a field name, the string “Field.” is prepended to the start of the string. Finally, to indicate that this string should be interpreted as an object name, as opposed to just a normal string of characters, the entire statement is enclosed in the @(string) construct.
C. Dynamic Naming for Other Objects
Here is another example using dynamic object naming, this time for a record. Although we don’t know the name of the record in advance, the ‘DBRecordName’ property can give us the name of the rowset’s primary record at run-time:
&semesterRec = @("&semesterRS.GetRow(&i)." | &semestersRS.DBRecordName);
And finally, here is an example of a ‘Transfer’ component statement in which the Menu Name, Bar Name, Item Name and Page Name have all been created dynamically:
Transfer( True, @("Menuname." | &transrec.MENUNAME.Value), @("BarName." | &transrec.BARNAME.Value), @("ItemName." | &transrec.BARITEMNAME.Value), @("Page." | &transrec.PNLITEMNAME.Value), &Action, &guid, &oper, &ver, &trxtype);
See Also:
Tip 024: Transfer Function