How to get recordtype name and ID without SOQL query

Feedback

In salesforce you are writing an apex class or trigger and you want that your logic to be work only for particular record type then you put IF condition in your code and in that IF condition you will check that this logic should works only for the particular recordtype, right ?

We can achieve that in multiple ways, we can fire a SOQL query and can fetch the recordtype name but SOQL query will count against your governor limits, the other work around is too use dynamic apex.  if you never heard about dynamic apex word before then you can read more about dynamic apex from here. Dynamic apex also been use frequently to create SOQL query, so the difference between traditional SOQL and Dynamic SOQL query is that for a any new field data you want to fetch you need to write the name of that field into your query but in dynamic apex you doesn’t required to add the name of the field, it will fetch the data of that field automatically but as of now we will not go in much detail about dynamic apex, so here we use dynamic apex to fetch the recordtype name information.

How To Access the RecordType Name

//This map contains the recordtype ID and its corresponding recordtype info like name
Map<ID,Schema.RecordTypeInfo> recordtypeMap= ObjectName.sObjectType.getDescribe().getRecordTypeInfosById();

for(ObjectName obj : Trigger.new)
{
  if(recordtypeMap.get(obj.recordTypeID).getName().containsIgnoreCase('RecordType Name')){
  //Do your stuff
  }
}

Replace ObjectName with your object name, it could be anything like account/case, so this is how you can easily can know the recordType name.
There is one more way to do the same using dynamic apex and which is,

for(ObjectName obj : trigger.new)
 {
 //Fetch the name and then use the below record type name anywhere in the logic
 string recordtypename = Schema.SObjectType.obj.getRecordTypeInfosById().get(obj.recordtypeid).getname();
 }

How To Access the RecordType ID

Accessing the RecordType ID is same as we access the RecordType Name, we just need to know the record type name whose ID we need to get then using that name with dynamic apex we can easily get the recordtype ID, see the below snippet code.


Id recordTypeId = Schema.SObjectType.Contact.getRecordTypeInfosByName().get('Record Type Name').getRecordTypeId();

 

In above snippet replace the Record Type Name with your object record type name whose ID you want to fetch.

This is how you can easily get the record type name and ID of the object without firing any SOQL query against the object as we know that SOQL query will count against the governor limit so we have tom minimize the SQOL query use in the code. Let me know if you have any questions regarding this, i will like to help you all.

 

Related Articles :

Speak Your Mind

*

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Optimization WordPress Plugins & Solutions by W3 EDGE