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.
 

3 comments:

  1. Use return type as Map and return sObjTypeDescribe.getRecordTypeInfosById(); to get the record type name based on the record id.

    ReplyDelete
  2. Awesome Blog, you have provided the right information that will be beneficial to us. Thanks for sharing your valuable Ideas to our vision. Linux Training in Chennai | Unix Training in Chennai | Python Training in Chennai

    ReplyDelete
  3. I really enjoy simply reading all of your weblogs. Simply wanted to inform you that you have people like me who appreciate your work. 
    Android Training Institute in Chennai | IOS Training in Chennai

    ReplyDelete