Tags

,

Suppose, we have 2 record types(Lets say Sales and Support) in Opportunity and when we create an Opportunity through APEX code, we need to populate the record type as Sales. We cannot hard code the record type Id in the code when we create the Opportunity as it varies based on Organization(Sandbox/Prod).

Following code would help to get the desired RecordTypeId:

Map sObjectMap = Schema.getGlobalDescribe();//This returns a map of all sObject names (keys) to sObject tokens (values) for the standard and custom objects defined in your organization.
Map recordType sObjectMap.get(‘Opportunity’).getDescribe().getRecordTypeInfosByName();//From the map sObjectMap, getDescribe which returns the describe result for Opportunity (contains all the describe properties for the sObject Opportunity) and getRecordTypeInfosByName method return maps that associate RecordTypeInfo with record IDs and record labels, respectively for Opportunity.
Id rtId = recordType.get(‘Sales’).getRecordTypeId();//getRecordTypeId returns the ID of the record type ‘Sales’.

There is another way to get the RecordType using SOQL(subjective to SOQL limit) which is as follows:

RecordType RecType = [Select Id From RecordType Where SobjectType = ‘Opportunity’ and DeveloperName = ‘Sales’];

There is a wonderful post in Salesforce Stackexchange about the best approach to get the recordtype id and the link for the same is RecordType Id best approach

Happy coding! Please let me know your comments as always.

Advertisements