We all know about the sObjects and their Fields in salesforce. But can we get a list of all the sObjects and respective fields in APEX? Yes, ofcourse we can, and that is what I’ll be showing you today. How to get the list of sObjects and their fields in salesforce. In order to understand the content of this blog, you will need to have an idea about map because we will be using basic map concepts.

APEX Code

public class objFieldList {
    public string selectedSObject { get; set;}
    
    public list getObjects(){
        list options = new list();
        map<string, SObjectType> objs = schema.getGlobalDescribe();
        for(string key: objs.keySet()){
            options.add(new selectoption(key,objs.get(key).getDescribe().getName()));
        }
        return options;
    }
    
    public void dummy(){
        
    }
    
    public map<string, string> getFieldList(){
        map<string, string> fieldList = new map<string, string>();
        if(selectedSObject != null){
            map<string,SObjectField> fList = schema.getGlobalDescribe().get(selectedSObject).getDescribe().fields.getMap();
            for(string str: fList.keySet()){
				fieldList.put(str, fList.get(str).getDescribe().getLabel());                
            }
        }else{
            return null;
        }
        return fieldList;
    }
}

In this code, we have used the schema class to get the list of sObjects and fields in APEX. This list is later displayed with the help of Map and SelectOptions in the next set of code snippet.

The schema class has the getGlobalDescribe() method which help us to get the schema of our entire salesforce org. This schema is essentially a map of object to their respective schema classes. We then call their respective describe and the same is done for getting the fields too.

VF Page

<apex:page controller="objFieldList">
    <apex:form>
        <apex:selectList value="{!selectedSObject}" size="1">
            <apex:selectOptions value="{!Objects}"/>
        </apex:selectList>
        <apex:commandButton action="{!dummy}" value="Show Fields"/>
    </apex:form>
    <apex:dataTable value="{!FieldList}" var="field" rendered="{!selectedSObject != null}">
        <apex:column value="{!field}"/>
        <apex:column value="{!FieldList[field]}"/>
    </apex:dataTable>
</apex:page>

Here we have displayed the list of Fields for selected sObjects.

Support

The output of my code will look something like this:

Support

That’s all about getting the list of sObjects and their respective fields in Salesforce APEX, for any further queries feel free to contact us at:

https://wedgecommerce.com/contact-us/

Or let us know your views about this blog in the comments section below.

Leave A Reply

Please verify that you are not a robot.

Tell us about Your Company

How can we help you with your business?




    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home