Friday 4 March 2016

How to Dynamically Retrieve RecordTypeId Without SOQL Query in Salesforce

Method 1:

You can directly create a new RecordType instance with RecordTypeLabel(Unique).

  1. Case myCase = new Case(
  2. Subject = 'Need Support',
  3. RecordType = new RecordType( Name = 'Support')
  4. );
  5. insert case;
         
Method 2:

You can use the below util, if you need a RecordTypeId.

Here is the RecordTypeUtility class, which will help you to retrieve RecordTypeId dynamically by providing "Object API Name" and "Record Type Label Name". 

        This common utility class will help you in many places without querying RecordTypeId by using SOQL.

  1. public class RecordTypeUtility{
  2.     public static Id getRecordTypeId(String objectAPIName, String recordTypeLabelName) {
  3.         try {
  4.             Map<String, Schema.SObjectType> sobjTypeMap = Schema.getGlobalDescribe();
  5.             Schema.SObjectType sobjectType = sobjTypeMap.get(objectAPIName);
  6.             return sobjectType.getDescribe().getRecordTypeInfosByName().get(recordTypeLabelName).getRecordTypeId();
  7.         }
  8.         catch(Exception ex) {
  9.             System.debug('## Exception found while getting record type name '+ex.getMessage());
  10.             return null;
  11.         }
  12.     }
  13. }

Example:

Accessing record type from standard object:

RecordTypeUtility.getRecordTypeId(‘Account’, ‘Student Account’);

Accessing record type from custom object:

RecordTypeUtility.getRecordTypeId(‘Business_Event__c’, ‘Day Event’);

2 comments:

  1. I was about to create something very similar, then I learned about:
    Case myCase = new Case(
    Subject = 'Need Support',
    RecordType = new RecordType( Name = 'Support')
    );
    insert case;
    Now I doubt if I need such an utility class at all.
    Kind regards,
    Szandor
    www.shoreforce.net

    ReplyDelete
  2. Hi Szandor,

    Your code snippet is very good(which is new to me). Thanks for your valuable comment and shared your thoughts.

    We can utilize the above util method, when if we need a RecordTypeId in apex class or somewhere else such as javascript button click(by making method as webservice).

    Let me know if any other options to get RecordTypeId without this util class.

    ReplyDelete

Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...