String Formatting with Macro and strFmt in Dynamics AX 2012
Published: October 7, 2020 at 5:38:45 PM UTC
This article describes some peculiar behavior in Dynamics AX 2012 when using a macro as format string in the strFmt, as well as examples on how to work around it.
The information in this post is based on Dynamics AX 2012 R3. It may or may not be valid for other versions.
I recently encountered an issue with the strFmt function that baffled me for a bit. The most baffling part was that I by some weird coincidence have never encountered it before in my many years as an Axapta/Dynamics AX developer.
The issue was that I tried to use a macro as the format string for the strFmt function and it just didn't work. It completely ignored the % parameters and only returned the remainder of the string.
After looking into it, I discovered that macros themselves can be used to format strings, which was also something I didn't know. Oh well, it's always good to learn something new, but I was still very surprised that I hadn't happened to come across this before.
Basically, something like this
;
info(strFmt(#FormatMacro, salesId, itemId, lineNum));
will not work because the % signs in the macro are actually used for the macro's own string formatting features. In this case, the strFmt function will see the formatting string as "--" and will therefore only return that.
Something like this:
info(#FormatMacro(salesId,itemId,lineNum));
will work, but probably not the way you want it to. Instead of outputting the values of the three variables, it will output the names of the variables instead, in this case "salesId-itemId-lineNum". (Notice that I didn't put spaces after the commas when passing parameters to the macro, as I usually do in method calls. That's because the macro will actually use such spaces as well, so the output would be "salesId- itemId- lineNum" if I did).
To actually use a macro as formatting string with strFmt, you need to escape the percentage signs with backslashes, like this:
;
info(strFmt(#FormatMacro, salesId, itemId, lineNum));
This will actually work as if you had supplied the format string directly.
This little job illustrates the examples:
{
#define.FormatMacro('%1-%2-%3')
#define.FormatMacroEscaped('\\%1-\\%2-\\%3')
SalesId salesId = '1';
ItemId itemId = '2';
LineNum lineNum = 3.00;
;
info(#FormatMacro(salesId,itemId,lineNum));
info(strFmt(#FormatMacro, salesId, itemId, lineNum));
info(strFmt(#FormatMacroEscaped, salesId, itemId, lineNum));
}