[SalesForce] How to retrieve all objects for org (Standard and Custom) and display them in picklist

I'm trying to write controller which will get all the standard and custom objects from org and display them in picklist; after selecting the Object name
from this Picklist – one PageblockTable should appear with related records below.

Best Answer

To get the list of all objects in your org, you can use something like this:

Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();

for(Schema.SObjectType thisObj : gd.values()) {
    System.debug(thisObj);
}

Run that in the Developer Console and you will see a long list of Object names:

Objects

Note this includes every object in your schema, including Custom objects and even things like Knowledge article types and field_history tracking objects...

Custom Objects

To put that into a picklist, in the Apex controller of your Visualforce page, instead of System.debug - build a list of Options:

public List<SelectOption> getObjectOptions(){
   List<SelectOption> options = new List<SelectOption>();
   Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();

    for(Schema.SObjectType thisObj : gd.values()) {
        options.add(new SelectOption(thisObj, thisObj));
    }

   return options;
}

and on your page:

<apex:selectList >
      <apex:selectOptions value="{!options}"/>
</apex:selectList>

Now you have a picklist of all your options.

Use actionFunction to run an "onclick" on that, or perhaps just some javascript, or a normal apex:button to submit the value back to the controller, and then use Schema again to get all the related lists for that object:

Map<string,string> childMap = new Map<String, String>();
List<Schema.Childrelationship> childList = Schema.getGlobalDescribe().get(selectedOption).getdescribe().getChildRelationships();

(where selectedOption is what was picked in the picklist).

Now you have a List of all the related object names! Use it as you will

(and don't forget test coverage!)

Related Topic