7

I want to work with Enums in my Apex code and I'm wondering what the usual practice is for storing their value in a database. Like java, you shouldn't store the ordinal as an int because that could change if you edit the Enum. Storing the value as a string is the obvious thing but there appears to be no valueOf(enum_name) method to take us back from the String to the Enum.

Does everyone doing this just write something like this because there is nothing built in?

http://wordgraphs.com/post/2910/Convert-string-to-enum-in-Apex

or is there a more intuitive way to store a selected enum element in the database?

Thanks!

7

Generally an enum would map to the picklist field type, and in that case I've seen a few implementations for dealing with this, some people just use string literals in their code - however that gets inflexible and hard to maintain very quickly.

Others use wrapper classes that have something like a .toSObject() method that marshalls the data into the SObject type, which would generally do this type of mapping.

I haven't seen it used to date, but you could use the Schema.PicklistEntry values for your field directly in your code, since they have a few advantages over enums:

  • New picklist values get a corresponding PickListEntry instance automatically - no code needed
  • They're a richer data type that can keep track of a few properties beyond what an enum can.
  • The getLabel() method will handle any localized translations for you, if any.
  • If somebody uses the API to set a picklist to an abitrary string (yes, you can do that) it shows up as an inactive picklist value, rather than failing to find a corresponding enum type.

However since you're limited to 100 getPicklistValues calls per transaction you'd be wise to build some sort of caching system if you use this pattern on a large scale app.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.