Salesforce Script To Fetch Object

7.11.2019
|
0 Comments
||
|

Salesforce script to fetch object which contains fields using fields API

When we work with objects in salesforce, sometimes we need a few things dynamically like a list of object names that contain field with a given API name of the field. So, here is a script that gives us all the objects which contain those fields.

String fieldAPI = 'fieldAPI__c';                       // API name of field to be searched  
List sObjectList = new List();

//fetching objects which will be used to get field names
for(Schema.SObjectType eachShema : Schema.getGlobalDescribe().Values()){
   String objectName = eachShema.getDescribe().getName();
   
   // Exclude all the unwanted sObjects e.g. History, Share etc..
    if(!objectName.containsignorecase('history') && !objectName.containsignorecase('tag')&&
        !objectName.containsignorecase('share') && !objectName.containsignorecase('feed')) { 	 
   	   sObjectList.add(objectName);  
      }
}

//Loop over object list to compare field names with desired field name
for(String sobject_type : SobjectList){
    Map global_describe = Schema.getGlobalDescribe();
    Map object_fields_map =   
                                  global_describe.get(sobject_type).getDescribe().fields.getMap();
    for(String key : object_fields_map.keyset()){
   	
                  if(key.equalsIgnoreCase(fieldAPI)){
                        //   …………..
   		 System.debug(sobject_type);
   		 System.debug(key);
   	      }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Share on:
Share this...
Share on Facebook
Facebook
Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin
Website security
Contact Us