Tips & Tricks Related To Schema For Fast And Dynamic Coding

Related to Object

Before starting the article, I would like to say to you please bookmark this article. So, you can easily able to access it when you need this. Let me tell you, why this is beneficial for you. Because I’ll update this article when I’ll get something more.

Get All Object:-
Map<String, Schema.SObjectType>schemaMap=Schema.getGlobalDescribe();
for(SObjectType obj: schemaMap.values()){
    if (obj.getDescribe().isCreateable() && obj.getDescribe().isUpdateable()) {
        System.debug('-->Object Name = '+obj.getDescribe().getLabel());
        System.debug('-->Object API Name = '+obj.getDescribe().getName());
    }
} 
Get Child Record From Inner Query Dynamically:-
List<Account> listOfAccount = [SELECT Id,Name,(SELECT Id,Name FROM Contacts) FROM Account LIMIT 1 ];
List<sObject> listOfChild = listOfAccount[0].getSObjects(childRelationshipName);

Related to Fields

Get All Field:-
Map<String, Schema.SObjectType> schemaMap=Schema.getGlobalDescribe();
Map<String,Schema.SObjectField> fieldMap=schemaMap.get(objectName).getDescribe().fields.getMap();
for(Schema.SObjectField obj : fieldMap.values()){
    if(obj.getDescribe().isCreateable() && obj.getDescribe().isUpdateable()){ 
           System.debug('--->Field Name ='+obj.getDescribe().getLabel()); 
           System.debug('--->Field API Name ='+obj.getDescribe().getName()); 
    }   
}  
Get the Field Type:-
1.
<String,Schema.SObjectField>objectFields=Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap();
Schema.DescribeFieldResult fieldLabel = objectFields.get(fieldName).getDescribe();
Schema.DisplayType dataType = fieldLabel.getType();
String fieldType = String.ValueOf(dataType);
System.debug('fieldType--> '+fieldType);

2.
Map<String,Schema.SObjectField> objectFields=Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap(); 
Schema.SObjectField field = objectFields.get(objectName);
Schema.DisplayType fieldType = field.getDescribe().getType(); 
System.debug('...fieldType '+fieldType);   

Related to Record Type

Get List Of All Record Types :-
Map<String,RecordTypeInfo> mapOfRecTypeInfo = Schema.getGlobalDescribe().get(objectName).getDescribe().getRecordTypeInfosByName();
        for(String recInfo:mapOfRecTypeInfo.keySet()){
            RecordTypeInfo recType = mapOfRecTypeInfo.get(recInfo);
          System.debug('==>Id'+recType.getRecordTypeId());
          System.debug('==>Id'+recType.getName());
        }
Get Record Type Id by Name:-
String recordTypeId= Schema.SObjectType.Account.getRecordTypeInfosByName().get(recordTypename).getRecordTypeId();
System.debug('--->recordTypeId '+recordTypeId);

I will update this article whenever I will get something for you. You can bookmark this article for future access. I hope you like and enjoy the article.