function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
StephenYS10000StephenYS10000 

Population of picklist using Apex code

Is it possible to populate the picklist using Apex code from a class or a trigger?

 

I appears that it can be done using the Salesforce API but I can't find any examples where this can be done directly in Salesforce using the native apex code.

 

Thanks

 

Stephen

Best Answer chosen by Admin (Salesforce Developers) 
hisrinuhisrinu
public List<SelectOption> getTypeOptions() 
{
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('None','--None--'));
Schema.DescribeFieldResult fieldResult = Account.Type.getDescribe();
List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
for(Schema.PicklistEntry p : ple)
options.add(new SelectOption(p.getValue(), p.getValue()));
return options;
}

All Answers

bob_buzzardbob_buzzard

You can populate a picklist field simply by assigning the picklist value string to the field.

 

 

hisrinuhisrinu
public List<SelectOption> getTypeOptions() 
{
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('None','--None--'));
Schema.DescribeFieldResult fieldResult = Account.Type.getDescribe();
List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
for(Schema.PicklistEntry p : ple)
options.add(new SelectOption(p.getValue(), p.getValue()));
return options;
}
This was selected as the best answer
StephenYS10000StephenYS10000

How would I use this in context of populating a field picklist then?

StephenYS10000StephenYS10000
Does this only apply to Visualforce pages?
JavajJavaj

Here is the working code for you:

 

 

VisualForce Page :

<apex:selectList value="{!PicklistValue}" size="1"  >
<apex:selectOptions value="{!Picklist}"  />
</apex:selectList>

 

 

Controller : 

 Public String PicklistValue{get;set;}
    
    public List<SelectOption> getPicklist() {
        List<SelectOption> options = new List<SelectOption>();
        Schema.DescribeFieldResult F = Contact.LeadSource.getDescribe();
             List<Schema.PicklistEntry> Ple = F.getPicklistValues();
             for(Schema.PicklistEntry p : ple){
                options.add(new SelectOption(p.getlabel(),p.getlabel()));
              }
        return options;
    }