Tuesday 1 January 2013

How to get Record Type Id without SOQL

Whenever we would like to fetch data from Database SOQL comes as first option in our mind but it will be added in query consumption limit. Here is a way to do this without any query:

// User need to pass two parameters SObject Type & 
    //RecordType Label ( not Record Type Developer Name)
    public static ID getRecordTypeId(String ObjectType, String RecordTypeLabel)
    { 
      SObject OBJ;
      // Describing Schema
      Schema.SObjectType Res = Schema.getGlobalDescribe().get(ObjectType);
      if (Res != null)
      {
  OBJ = Res.newSObject();
  // Describing Object 
  Schema.DescribeSObjectResult DesRes = OBJ.getSObjectType().getDescribe(); 
  if (DesRes != null)
  {
            Map RecordTypeMap =      DesRes.getRecordTypeInfosByName();
     if (RecordTypeMap != null) 
     {
        Schema.RecordTypeInfo RecordTypeRes = RecordTypeMap.get(RecordTypeLabel);
        if (RecordTypeRes != null) 
        {
           return RecordTypeRes.getRecordTypeId();
        }
      }
   }
        }
 return null;
    } 
Let's say there are two Record Type of Account so we can get Record Type ID of Account Like this
ID RecordTypeId = getRecordTypeId('Account' , 'RecordType1');

Best Regards
Sandeep

No comments:

Post a Comment