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
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
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.