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’);