10/08/2014

Getting List of Objects from Apex Picking the right API

Situation:

In many scenarios, there is a requirement to retrieve a list of objects in an organization to process them. Apex has a class called Schema. It contains the entire schema of your organization. Objects, their fields, field type etc. can all be retrieved using this class.

 

This can be very useful. Suppose you want to create a dropdown menu and bind the list of objects in your organizations to it. You may also want to generate a list of fields when you select an object in the first dropdown.

Recipe:

The following code shows how to generate a list of objects:

 

<apex:page controller=”objectList” >
<apex:form >
<apex:SelectList value=”{!val}” size=”1″>
<apex:selectOptions value=”{!Name}”></apex:selectOptions>
</apex:SelectList>
</apex:form>
</apex:page>

 

The Visualforce page uses the following Apex class as its controller:

 

public class objectList{
public String val {get;set;}
public List<SelectOption>v getName()
{
List<Schema.SObjectType> gd = Schema.getGlobalDescribe().Values();
List<SelectOption> options = new List<SelectOption>();
for(Schema.SObjectType f : gd)
{
options.add(new SelectOption(f.getDescribe().getLabel(),f.getDescribe().getLabel()));
}
return options;
}
}

Findings

  • This will generate all the objects in your organization. You can restrict them. For example if you want to retrieve only custom objects, you can place a check to ensure that only objects that contain ‘__c’ should be added in the list.

 

Source: http://developer.salesforce.com