3

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.

1 Answer 1

10

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;
}
2
  • 5
    if you try returning enum value back from Apex to lightning controller it returns blank object as well. Dec 9, 2018 at 20:43
  • 1
    I'd suggest that if toMode doesn't find an appropriate enumeration value, then that should be an exception rather than a null. Bear in mind, if you could pass enumerations, then an invalid value would probably be a compile error. Remember: Friends don't let friends return null. Feb 9 at 11:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .