Building Reusable Picklist Methods in Apex for Efficient Salesforce Development

by Rijwan Mohmmed
0 comment
how-to-create-reusable-picklist-method-in-apex

Hello friends, today we will learn to Building Reusable Picklist Methods in Apex for Efficient Salesforce Development. We can easily create a dynamic reusable picklist method so we can get many picklist values by one method.

Also check this : Effortlessly Retrieve Related List Records in Salesforce LWC

Key Highlights:

  1. Consistency: Centralize picklist management to ensure uniform behavior across different components and processes.
  2. Maintainability: Update picklist logic in one place instead of modifying multiple code segments.
  3. Efficiency: Reduce code duplication and simplify maintenance by reusing methods across different classes and triggers.
  4. Flexibility: Adapt picklist values and logic as requirements change without extensive refactoring.

Apex Class : reusablePicklist.apxc

 public class reusablePicklist{

      public string country{get;set;}
      public static List<SelectOption> globSelectOption(string objectApiName, String fieldApi) {
    
        List<SelectOption> optionList = new List<SelectOption>();
        optionList.add(new selectOption('', '--None--'));
        Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objectApiName);
        Sobject objectApi = targetType.newSObject();
        Schema.sObjectType objType = objectApi.getSObjectType(); 
        Schema.DescribeSObjectResult objDescribe = objType.getDescribe(); 
        map<String, Schema.SObjectField> fieldMap = objDescribe.fields.getMap(); 
        list<Schema.PicklistEntry> values =fieldMap.get(fieldApi).getDescribe().getPickListValues();
        for (Schema.PicklistEntry ple : fieldMap.get(fieldApi).getDescribe().getPickListValues()) {
            optionList.add(new SelectOption(ple.getvalue(), ple.getLabel()));
        }
        return optionList;
    }
	
	/************/
	public List<SelectOption> getCountryPicklist(){
		return globSelectOption('Account','Country__c');
	}
	/************/
 }	

Visualforce Page: reusablePicklist.vfp

<apex:page controller="reusablePicklist"  showHeader="false" sidebar="false">
   <apex:selectList  size="1" value="{!country}" id="countryid">
      <apex:selectOptions value="{!CountryPicklist}"/>
   </apex:selectList>
</apex:page>

Reference :

  1. Salesforce Picklist
What’s your Reaction?
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

You may also like

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.