How to: Retrieve a list of sObjects in Apex
Osama | May 11, 2010Some one asked me how to retrieve a list of sObjects in an SF organization using Apex and bind it to a picklist in a VisualForce page.
List of sObjects is returned when you hit the schema of your SF organization. You can get the Label of sObjects as well as API names.
The following code snippet shows how to do the above mentioned task
VisualForce page:
<apex:page controller="Schema2" >
<apex:form >
<apex:SelectList value="{!val}" size="1">
<apex:selectOptions value="{!Name}"></apex:selectOptions>
</apex:SelectList>
</apex:form>
</apex:page>
Apex Controller Code:
public class Schema2 {
public String val {get;set;}
public List<SelectOption> getName()
{
List<Schema.SObjectType> gd = Schema.getGlobalDescribe().Values(); //extracts the List of sObjects in an organization
List<SelectOption> options = new List<SelectOption>();
for(Schema.SObjectType f : gd)
{
options.add(new SelectOption(f.getDescribe().getLabel(), f.getDescribe().getLabel()));
}
return options;
}
}
Feel free to ask any questions









