Search code examples
enumsaxaptadynamics-ax-2012

Look up Enum by label instead of by value


Is there a quick way to look up an Enum with only using the label of the enum instead of the value. Let's say the Enum type is SalesStatus, I want to be able to basically call into some kind of a function like enumLabel2Value(enumStr(SalesStatus), "Open order") and it will return 1.

I'm trying to avoid looping thru all possible values and checking each one separately, it seems like this should be something that's readily available since whenever a user filters on a enum column on a grid, they enter in the label, not the value, but I haven't seen anything like it.


Solution

  • You can use the str2Enum function for that. From the documentation:

    Retrieves the enum element whose localized Label property value matches the input string.

    In addition to the caveats from Alex Kwitny's answer, I recommend taking a look at the comments of the documentation, specifically the comment

    Please note that str2Enum performs partial matching and matches the beginning of the string. If there are multiple matches, it will take the first one.

    In addition take a look at method string2Enum of class DMFEntityBase, which supports different options how the enum element can be specified. I think with the DictEnum.name2Value() method enum elements specified by their label are handled.

    Update

    OP mentioned in the comments to Alex Kwitny's answer that it is a specific enum ExchangeRateDisplayFactor he has issues with. str2Enum also works with that enum, as the following job demonstrates:

    static void str2EnumTest(Args _args)
    {
        ExchangeRateDisplayFactor factor;
    
        factor = str2Enum(factor, '1');
        info(strFmt('%1', factor)); // outputs '1'
        factor = str2Enum(factor, '10');
        info(strFmt('%1', factor)); // outputs '10'
        factor = str2Enum(factor, '100');
        info(strFmt('%1', factor)); // outputs '100'
        factor = str2Enum(factor, '1000');
        info(strFmt('%1', factor)); // outputs '1000'
        factor = str2Enum(factor, '10000');
        info(strFmt('%1', factor)); // outputs '10000'
    }