Create a generic method that passes the object and field name and gets values as a list

We as developers, often face poorly written code. Therefore when we build the code, we want to build it smartly, so it won’t result in additional costs and time.

Scenario: Retrieve values from a picklist in a specific object.
What we want to achieve here is to retrieve the values from a picklist and use them in the code.

First, add the method below in a <yourObjectName> class that contains all generic methods.

 public static List<String> getPicklistValues(String objName, String fieldName){

       SObjectType objectType = Schema.getGlobalDescribe().get(objName);
       Map<String,Schema.SObjectField> mfields = objectType.getDescribe().fields.getMap();
       Schema.DescribeFieldResult fieldResult = mfields.get(fieldName).getDescribe();
       List<String> picklistValuesList = new List<String>();
       List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
       for(Schema.PicklistEntry pickListVal : ple){
           picklistValuesList.add(pickListVal.getLabel());
       }

       return picklistValuesList;
}

Second, use the generated method in a class where you want to retrieve a specific logic.

listPackagingScopeValues = yourClassName.getPicklistValues('yourObjectName', 'yourFieldName';
  • yourClassName – is the name of the class where you stored the generic method.
  • yourObjectName – is the name of the object that you want to use.
  • yourFieldName – is the name of the field that is in yourObjectName that you want to use.
Want to learn more?

Learn about How to write your first Salesforce Apex trigger
Read more about Apex Developer Guide – Maps
Check out this Trail: Define Sets and Maps

Share this article...

Salesforce Maniac for 7 years, Hardcore Admin & Developer, Geek, Animal lover, and dog & cat rescuer activist. Lifetime student, Stand-Up comedian wannabe, Photographer, Gamer, Anime lover, and coffee addict. Spreading salesforce love and teaching beyond my capacity. Aiming to become Tech Architect!

Leave a Reply

Your email address will not be published. Required fields are marked *