function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Henrique RodriguesHenrique Rodrigues 

How to insert values in a object with RecordType?

Hello everyone, i'm coding a test class and I have a 'insert' in the account object that have a RecortType, how can I reference the Record Type to insert?

The error is: System.DmlException: Insert failed. First exception on row 0; first error: INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST, bad value for restricted picklist field: Warehouse: [Type2__c]
 
Account ac = new Account();
        ac.Name = 'Account';
        ac.Type2__c = 'Warehouse';
        ac.Country2__c = ct.Id;
        ac.City__c = city.Id;
        ac.Oracle_Code__c = '1';
        
        insert ac;


 
Varun SinghVarun Singh
Hi Henrique Rodrigues

Get  Record type using scema

Id recordTypeId = Schema.SObjectType.OBJECT_NAME.getRecordTypeInfosByName().get('RECORD_TYPE_NAME').getRecordTypeId();
 
Id recordTypeId = Schema.SObjectType.OBJECT_NAME.getRecordTypeInfosByName().get('RECORD_TYPE_NAME').getRecordTypeId();
//For Account object you can use in this way 
Id recordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName() .get('Student').getRecordTypeId();
//then assign record type to account
ac.RecordTypeId = recordTypeId;

 
Amit Chaudhary 8Amit Chaudhary 8
Try to update your code like below
Id accRecType = Schema.SObjectType.Account.getRecordTypeInfosByName().get('RECORDTYPE_NAME').getRecordTypeId();

Account ac = new Account();
ac.Name = 'Account';
ac.Type2__c = 'Warehouse'; // You need to Enter Valid Picklist value
ac.Country2__c = ct.Id;
ac.City__c = city.Id;
ac.Oracle_Code__c = '1';
ac.recordTypeId = accRecType;
insert ac;

Let us know if this will help you