0

I have a custom object with two record types, How can I set the record type using the record type name when creating a new object record??

Without using the RecordTypeId is possible?? I think is not a good practice Isn't it?

A lot of thanks

3
  • You profile has default recordTypeId, it would be set when you create record – Pranay Jaiswal Dec 27 '19 at 11:59
  • And how I set or change the recordtype using the recordtype name? Is that possible – Mar Andrés López Dec 27 '19 at 12:03
  • 2
    Why do you want to use RecordType Name instead of Id? – tugce Dec 27 '19 at 13:06
6

There's not any way (at least, not that I know of) to completely take the recordTypeId out of the equation, but there is a way to use the record type's name to get at the appropriate Id.

Specifically, the SObject's "describe" information, via the DescribeSObjectResult class provides several methods to get record type information.

Probably the most common way to use this is something like this

Id myRecTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('My Record Type Label').getRecordTypeId();
// Schema.SObjectType.Account gets you the DescribeSObjectResult (for the Account SObject in this case)
// (You could use Account.SObjectType.getDescribe() instead to get the DescribeSObjectResult)
// getRecordTypeInfosByName() gets you a Map<String, RecordTypeInfo> where the keys of the map
//   are the record type labels (i.e. keep any spaces in the name as spaces instead of underscores)
// getRecordTypeId() gets you, well...the record type's Id
4

You can use the name directly without a describe call:

Object__c record = new Object__c(Name='Demo', RecordType=new RecordType(Name='SomeType'));

Note that this technique only works if the record type game is globally unique in your org across all sObject types.

Otherwise, you can, and should, use a describe call to get the Id dynamically, as noted in the other answer.

Not the answer you're looking for? Browse other questions tagged or ask your own question.