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
Jim BoudreauxJim Boudreaux 

Dynamic Apex Help

I want to write code that does stuff based on the choices in a picklist. I know all the choices in a picklist and of course I could hardcode it, but I want to be able to edit the picklist choices without breaking my code.

 

Example:

 

Let's say I have a custom object that has a picklist value named "Mood" with the options of "Happy", "Sad" and "Fine". Next I have a visualforce page with a table with totals for each mood.

 

I could easily write code in the VF controller that pulls all my records, and iterates through each with a if statement that checks the mood and totals them.

 

The problem there is if I ever add another mood to the picklist, I would then have to edit my vf page and the controller apex to reflect the additional moods.

 

It would be a lot nicer to be able, in apex, to get a list of the picklist options and then iterate through those and run the tallying code.

 

 

This is not my specific usecase, but it illustrates it nicely. Could someone out there help me out? 

Oh, and FYI, I through this code in there:

 

 

schema.describefieldresult f = schema.sobjecttype.my_custom_object__c.fields.my_custom_field__c;

 

but I get an error page saying, System.Exception: Too many fields describes: 11 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
wesnoltewesnolte

Hey

 

Something like this?

 

public List<SelectOption> getCountries()
{
  List<SelectOption> options = new List<SelectOption>();
        
   Schema.DescribeFieldResult fieldResult =
 OfficeLocation__c.Country__c.getDescribe();
   List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        
   for( Schema.PicklistEntry f : ple)
   {
      options.add(new SelectOption(f.getLabel(), f.getValue()));
   }       
   return options;

} 

 

Cheers,

Wes 

All Answers

wesnoltewesnolte

Hey

 

Something like this?

 

public List<SelectOption> getCountries()
{
  List<SelectOption> options = new List<SelectOption>();
        
   Schema.DescribeFieldResult fieldResult =
 OfficeLocation__c.Country__c.getDescribe();
   List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        
   for( Schema.PicklistEntry f : ple)
   {
      options.add(new SelectOption(f.getLabel(), f.getValue()));
   }       
   return options;

} 

 

Cheers,

Wes 

This was selected as the best answer
Jim BoudreauxJim Boudreaux

Thanks wesnolte, I adapted your code to fit my circumstances, and it worked like a charm.

 

One more question though. Lets say the choices in your picklist are filtered based on a recordtype, is there a way to filter the results of your example based on recordtype?