Method 1:
You can directly create a new RecordType instance with RecordTypeLabel(Unique).
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".
You can directly create a new RecordType instance with RecordTypeLabel(Unique).
- Case myCase = new Case(
- Subject = 'Need Support',
- RecordType = new RecordType( Name = 'Support')
- );
- 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.
- public class RecordTypeUtility{
- public static Id getRecordTypeId(String objectAPIName, String recordTypeLabelName) {
- try {
- Map<String, Schema.SObjectType> sobjTypeMap = Schema.getGlobalDescribe();
- Schema.SObjectType sobjectType = sobjTypeMap.get(objectAPIName);
- return sobjectType.getDescribe().getRecordTypeInfosByName().get(recordTypeLabelName).getRecordTypeId();
- }
- catch(Exception ex) {
- System.debug('## Exception found while getting record type name '+ex.getMessage());
- return null;
- }
- }
- }
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’);
I was about to create something very similar, then I learned about:
ReplyDeleteCase 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
Hi Szandor,
ReplyDeleteYour 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.