Saturday 1 December 2012

How to create a record of a particular record type in Controller and Test class


Here i am taking an example of Account(Object) and Person Account (Record Type).

Controller:

public class personAccountClass{
public void createPersonAccount(){
Account acc = new Account();
acc.lastName = 'test';
RecordType rt =Database.Query('Select id from RecordType where Name = \'Person Account\' and          
   sObjectType  =  \'Account\'and IsPersonType=True');
acc.RecordTypeid = rt.id;                
insert acc;
}
}

Test class:

@isTestprivate
class testClass{  
static testMethod void testGetAccountDetails(){      
RecordType rType = new RecordType(Name='Person Account',sObjectType='Account');
       List<RecordType> AccountRTypes = Database.Query('Select id, Name, sObjectType from      
 RecordType where Name = \'Person Account\' and sObjectType = \'Account\'and 
IsPersonType=True');

Map<String,String> AccountRecordTypes = new Map<String,String>{};      
for(RecordType rt: AccountRTypes){                      
AccountRecordTypes.put(rt.Name,rt.Id);
           }      

Account acc = new Account();      
acc.LastName = 'test';      
acc.RecordTypeid= AccountRecordTypes.get('Person Account');
insert(acc);
}
}


The record type id can also found by below syntax without using a SOQL:

Id recordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Person Account').getRecordTypeId();

No comments:

Post a Comment