Apex: Dynamically get fields for an SObject - no hardcoding

  • It states in Salesforce Apex docs that I can get fields for a particular SObject (standard or custom) in the following way:

    Map<String, Schema.SObjectField> M = Schema.SObjectType.Custom__c.fields.getMap();
    

    But this requires hardcoding. as I need to hardcode the API name of the SObject : Schema.SObjectType.

    Is there a way to access all fields on an SObject dynamically without hard coding? I am getting a list of all SObjects in my org by calling Schema.getGlobalDescribe(), but this leaves me with API names of individual SObjects. There is no way to get all those SObject's field info dynamically. Am I missing something or it is just not possible?

    I want something like:

    List <Schema.SObjectField> fieldList = Schema.SObjectType.get(SObject_API_Name).fields;
    
  • You don't need to hard code the Object name as you have specified, you can indeed do it dynamically, for example:

    SObjectType accountType = Schema.getGlobalDescribe().get('Account');
    Map<String,Schema.SObjectField> mfields = accountType.getDescribe().fields.getMap();
    

    Thanks! Exactly what I was looking for. But somehow I weren't able to find the getGlobalDescribe().get(strname) flavour of this in SF docs ... although the hardcoded example is pretty common. Thanks again.

    `getGlobalDescribe` returns a `Map`, so you're using the Map class's get method.

  • The docs suggest you use the newer Schema.describeSObjects(List) method - that lets you pass one or more names of objects as a list, and get back the results. Here's the sample code:

    // sObject types to describe
    String[] types = new String[]{'Account','Merchandise__c'};
    // Make the describe call
    Schema.DescribeSobjectResult[] results = Schema.describeSObjects(types);
    System.debug('Got describe information for ' + results.size() + ' sObjects.');
    // For each returned result, get some info
    for(Schema.DescribeSobjectResult res : results) {
        System.debug('sObject Label: ' + res.getLabel());
        System.debug('Number of fields: ' + res.fields.getMap().size());
        System.debug(res.isCustom() ? 'This is a custom object.' : 'This is a standard object.');
        // Get child relationships
        Schema.ChildRelationship[] rels = res.getChildRelationships();
        if (rels.size() > 0) {
            System.debug(res.getName() + ' has ' + rels.size() + ' child relationships.');
        }
    }
    

    Faster than describe global when you know the names you're looking for, important for the new governor limits.

  • You can use Schema.SObjectType to get the object type dynamically:

    String obj = 'Account';
    
    Map<String,Schema.SObjectType> gd = Schema.getGlobalDescribe(); 
    Schema.SObjectType sobjType = gd.get(obj); 
    Schema.DescribeSObjectResult describeResult = sobjType.getDescribe(); 
    Map<String,Schema.SObjectField> fieldsMap = describeResult.fields.getMap(); 
    
  • String sobjectname = 'Case' ; //object api name
    String fieldapiName = 'Status'; //Field api name
    String fieldTypeName = Schema.getGlobalDescribe().get(sobjectname).getDescribe().fields.getMap().get(fieldApiName).getDescribe().getType().name().toupperCase(); 
    System.debug('*** fieldTypeName = ' + fieldTypeName);       
    
  • The Summer '16 release has a nice function to retrieve populated fields from an object: getPopulatedFieldsAsMap()

    I had a simple use case of generating a CSV file from an arbitrary list of sObjects for which it provided an easy solution.

    Using getPopulatedFieldsAsMap() you can retrieve a map of field names and their corresponding values without knowing the object type.

    sObject data = [SELECT Id, Name FROM Lead LIMIT 1];
    Map<String, Object> fieldsAndValues = data.getPopulatedFieldsAsMap();
    

    This doesn't really answer the question. It doesn't give you all fields on the object, only a subset of them. And you need actual records.

    @AdrianLarson , may I know what you mean by subset . Because I check release note https://releasenotes.docs.salesforce.com/en-us/summer16/release-notes/rn_apex_sobject_getmap.htm , it does not state limitation. However I stil face some of the field is not return although class version is 46.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM