Retrieve a List of Objects using Apex

Source code:

Problem

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.

Solution

The following code shows how to generate a list of objects. First create a Visualforce page as shown:

[code apex] [/code]

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

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

Discussion

  • 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.