2

In my apex class and trigger code I have If statements based on picklist values. Using picklists in code I know uses the api name of the picklist value.

My question is, is it ok to just use the api name or is it better to create custom metadata? So if my picklist consists of 2 values for example:

Values | API Name

Old stuff  |  Old
New stuff  |  New

Is is good enough to just write the code like this:

If (act.status__c = 'Old'){ 
   act.status = 'New';
}

which is basically hard-coding, which I don't like to do, even if it's using the API name. If I create custom metadata, I still end up checking actual values though so it doesn't seem better. Is there a better way to check and set picklist values in code?

I should mention that my picklist has many values - it's the Status for Orders and there are several for the 'Draft' option as well as for the 'Activated' option.

  • setup a common class file to maintain all picklist value constants. You will need to define them as public static final string variables in order to access them directly using the class name – sanket kumar Sep 4 '18 at 3:21
1

We create Apex enum-style wrappers for picklist field values so that we have compile-time constants for those values as well as convenient access to the values' labels, active state, and notion of which value is the default. We included the base class for these enums in our sirono-common open source Apex class library:

https://github.com/blueprinthealth/sirono-common#apex-picklist-enums

Take a look and, if you decide to go that route, let me know if you have any questions about the approach.

| improve this answer | |
  • Thanks Scott, but I should've added (have now) that my picklist is not a simple one, but has many values (29 currently). Not all are referenced in code, only about 6 of them. – Irene Sep 4 '18 at 3:44
  • @Irene - you can define the enum to be whatever list of picklist values you need to check - it doesn't have to be the full list – cropredy Sep 4 '18 at 3:59
  • Yes, @cropredy is correct...at least with sirono-common picklist enums, you aren't required to create Apex enum constants for all values of the picklist field. It's fine to include only those you actually reference from Apex. Note that the PicklistEnum base class will internally create entries for all values reported by metadata, but it's up to you which are "proxied" into Apex as enum constants. – Scott Wells Sep 4 '18 at 20:59

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.