Create an Apex Code Method to Pass Object and Field Name and Retrieve Values as a List

As developers, we often encounter poorly written code that leads to maintenance challenges, increased costs, and wasted time. Writing efficient and scalable Apex code is essential to ensure long-term maintainability and optimal performance in Salesforce development. One common scenario developers face is retrieving values from a picklist in a specific object and utilizing them dynamically in their code.

Scenario: Retrieve Values from a Picklist in a Specific Object

Our goal is to extract picklist values from a given object and use them within our Apex code to enhance automation, validation, or other business logic.

To achieve this, start by adding the following method to 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;
}

Next, implement the generated method in a class where you need specific business logic or data retrieval. This integrates the method into your workflow.

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 more about apex code 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...

As Managing Partner and CTO at codeSTREETS, I help global businesses scale through robust Salesforce architecture and custom software solutions. With 10+ years of experience in enterprise transformation, I lead teams to deliver results-driven, future-ready digital platforms. My expertise spans cloud architecture, product innovation, and mentorship, earning recognition as a speaker and community leader. Let’s connect if you’re seeking tailored solutions, seamless implementation, or strategic partnerships to accelerate your business growth.

Leave a Reply

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