How to set record type of records while saving the records?
SUMMER '18 UPDATE
You can now use the
getRecordTypeInfosByDeveloperName()
to get a Record Type Id by Developer Name without spending a SOQL query. This should be the preferred approach going forward instead of using the oldgetRecordTypeInfosByName()
method as suggested in the original answer.
Use this approach instead of the old suggestion below, unless you are really trying to get the Record Type Id by RECORD_TYPE_NAME
(Label). The rest of the answer still applies:
Id recordTypeId = Schema.SObjectType.OBJECT_NAME.getRecordTypeInfosByDeveloperName()
.get('RECORD_TYPE_DEVELOPER_NAME').getRecordTypeId();
You can obtain a Record Type in code in the following way:
Id recordTypeId = Schema.SObjectType.OBJECT_NAME.getRecordTypeInfosByName()
.get('RECORD_TYPE_NAME').getRecordTypeId();
Just replace the OBJECT_NAME
with your object (e.g - Account
), and the RECORD_TYPE_NAME
with the record type name for that object.
In order to assign this Record Type to a specific record you can use the RecordTypeId
field. Here's an example for Account
:
Account acc = new Account(Name='Test Account', RecordTypeId = recordTypeId);
or through a property like this:
acc.RecordTypeId = recordTypeId;
UPDATE
In your case you can obtain the recordTypeId
like this:
Id recordTypeId = Schema.SObjectType.Grant_Report__c.getRecordTypeInfosByName()
.get('Matching Fund Cash').getRecordTypeId();
And then just assign this recordTypeId
to RecordTypeId
field of the records in your FOR
loops that you need to update. I'm assuming that's in the saveDoc()
method:
Public Pagereference savedoc(){
Id recordTypeId = Schema.SObjectType.Grant_Report__c.getRecordTypeInfosByName()
.get('Matching Fund Cash').getRecordTypeId();
List<Grant_Report__c> allGrantReports = new List<Grant_Report__c>();
for(Grant_Report__c gr: grCashObjLst){
if(gr.id==null)
{
gr.Grant_Approval__c= ids;
}
gr.RecordTypeId = recordTypeId;//assign record type
allGrantReports.add(gr);
}
for(Grant_Report__c gr: grInKindObjLst){
if(gr.id==null)
{
gr.Grant_Approval__c= ids;
}
gr.RecordTypeId = recordTypeId;//assign record type
allGrantReports.add(gr);
}
for(Grant_Report__c gr: grExpenseObjLst){
if(gr.id==null)
{
gr.Grant_Approval__c= ids;
}
gr.RecordTypeId = recordTypeId;//assign record type
allGrantReports.add(gr);
}
grExpenseObjLst=null;
try{
upsert gaObj;
//saved you 2 DML statements here by joining 3 lists to 1
upsert allGrantReports ;
}catch(System.DMLException e) {
ApexPages.addMessages(e);
return null;
}
return NULL;
}
UPDATE 2
NOTE: No need to use this approach after Summer '18 update
In case you want to get Record Type by developer name, you'll have to use a DML statement:
Id recordTypeId = [select Id from RecordType where DeveloperName = 'Matching_Fund_Cash' AND sObjectType = 'Grant_Report__c' limit 1].Id;