[SalesForce] Pass an enum value from lightning controller to Apex

Is it possible to pass an enum value from lightning controller to Apex?

Here is what I tried

lightning component part

    const action = component.get("methodC");
    action.setParams({p: "VIEW"});
    action.setCallback(component, function(){});
    $A.getCallback(function(){$A.enqueueAction(action);})();

apex part

public enum Mode { CREATE, VIEW, EDIT }

@AuraEnabled
public static void methodC(Mode p) {
    System.debug('p:' + p);
}

And here is the error I am getting:

16:35:58:002 FATAL_ERROR System.JSONException: Illegal value for primitive

enter image description here

Would be grateful for any relevant documentation on the topic. Here is what I was able to find, but it is of no use for my question about lightning client-side and Apex enum.

Thank you.

Best Answer

The types that can be passed are limited, leaving you to have to do more work than ideal sometimes.

In this case, code like this should work:

@AuraEnabled
public static void methodC(String p) {
    Mode pMode = toMode(p);
    ...
}

private static Mode toMode(String s) {
    for (Mode m : Mode.values()) {
        if (m.name() == s) return m;
    }
    return null;
}
Related Topic