New Batch#100 (10th Nov 2021) - Salesforce Admin + Dev Training (WhatsApp: +91 - 8087988044) :https://t.co/p4F3oeQagK

Friday 26 December 2014

Fetching Record Type Id with Dynamic Apex

recordTypeInfo Utility Method
  public class MyUtility {
   /*
      @ Description -
      To fetch the RecordType Information of a certain Object.
      @Usage -
      Using this approach, we can avoid writing SOQL queries in apex class/test class to fetch the record type Id.
   */

   /*** recordTypeInfo Utility Method ***/
   //Below method will take sObject API as input.
   public static Map recordTypeInfo(String objectApiName){
    
    Map sObjectMap = Schema.getGlobalDescribe() ;
    Schema.SObjectType sObjType = sObjectMap.get(ObjectApiName) ;
    Schema.DescribeSObjectResult sObjTypeDescribe = sObjType.getDescribe() ;
    
    //returns all the record types info for a certain object
    return sObjTypeDescribe.getRecordTypeInfosByName();
    
   }
  }
  //---End of the Logic---Please ignore remaining lines---
 

recordTypeInfo Utility Method - Usage
  /*** recordTypeInfo Utility Method - Usage ***/

  //To retrieve the recordTypeId of a RecordType 'Sample Record Type' which belongs to 'Case' object.
  Id sampleRtId = MyUtility.recordTypeInfo('Case').get('Sample Record Type').getRecordTypeId();

  //Result: 'sampleRtId' will fetch the recordTypeId of 'Sample Record Type' record type.