Ad Code

How to get list of objects in salesforce

How to get list of standard and custom objects in salesforce


Most of the time we work on querying single objects like Account, Contacts, etc., in Salesforce and rarely get an opportunity to query the list of objects or entity definition itself. Isn’t it? 

Well, it’s time to explore different methods to retrieve a list of standard and custom objects and a list of all fields in the Apex code. This post is applicable for both classic and lightning framework, as we are dealing with Apex.


Get all objects [Standard and custom objects]

    public static map<string, string> getAllObjects(){
        map<string, string> objectList = new map<string, string>();
        for ( Schema.SObjectType o : Schema.getGlobalDescribe().values() )
        {
            Schema.DescribeSObjectResult objResult = o.getDescribe();
            objectList.put(objResult.getName(), objResult.getLabel());
        }
        return objectList;
    } 

In the above-mentioned code, we are adding each object label and its API name to the map. In case if you want to get only custom objects you can use contains('__C') filter to the objResult.getName()  



Get a list of objects by passing an API text string

    public static map<string, string> getAllObjects(string searchString){
        searchString = searchString + '%';
        system.debug(searchString);
        map<string, string> objectList = new map<string, string>();
        List<EntityDefinition> objList = [select MasterLabel, QualifiedApiName from EntityDefinition where QualifiedApiName
                                          like:searchString order by MasterLabel asc];
        system.debug(objList.size());
        for(EntityDefinition ent: objList){
            objectList.put(ent.QualifiedApiName, ent.MasterLabel);
        }
        return objectList;
    }

In this code, we are passing a string to the method and querying EntityDefinition object to get a list of objects that match the criteria. 



Get a list of fields by passing object API name

  public static List<string> getFieldsByObjectName(String objectName){
        list<string> fieldList = new  list<string>();
        Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
        Map <String, Schema.SObjectField> fieldMap = schemaMap.get(objectName).getDescribe().fields.getMap();
        for(Schema.SObjectField sfield : fieldMap.Values())
        {
            schema.describefieldresult dfield = sfield.getDescribe();
            fieldList.add(dfield.getLabel());
        }
        return fieldList;

    }


Here we are getting all the fields from the object by passing the object name as an input parameter. 


Great. In this post, we have learned an easy way to get a list of standard and custom objects and also a list of fields in the Salesforce Apex code.

Post a Comment

2 Comments