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
abeparabepar 

record type doesn't get set in Apex

In a test class, I am trying to create an opportunity of a specified record type. 

 

   //create opportunity record
        String opportunityName= 'xxxx';
            Opportunity o = new Opportunity(
            AccountId=a.Id, 
            Name=opportunityName, 
            StageName='Prospecting', 
            CloseDate=Date.today(),
            Opportunity_Type__c='New',
            LeadSource='xxx',
            RecordTypeId= [Select Id From RecordType Where Name = 'xxx' and SobjectType= 'Opportunity'].Id);
            
        insert o;
        system.debug(o.RecordType.Name);
        

 

However this returns- null in the debug statement. I'm sure i'm overlooking something simple. Any help?

Saikishore Reddy AengareddySaikishore Reddy Aengareddy

You will need to explicitly query when you want related object field values..

 

...

...

insert o;

 

opportunity opp = [select recordType.name from opportunity where Id = :o.Id];

system.debug(opp.recordType.Name);

Afzal MohammadAfzal Mohammad

Well, if you are writing a testmethod. Then, how about creating a recordtype before creating an opportunity?

 

//create a recordtype
RecordType rt = new RecordType(Name='xxx', SObjectType='Opportunity');
insert rt;

//create opportunity record
        String opportunityName= 'xxxx';
            Opportunity o = new Opportunity(
            AccountId=a.Id, 
            Name=opportunityName, 
            StageName='Prospecting', 
            CloseDate=Date.today(),
            Opportunity_Type__c='New',
            LeadSource='xxx',
            RecordTypeId= rt.Id;
            
        insert o;
        system.debug(o.RecordType.Name);

 Hope that helps.

RockzzRockzz
RecordType rt = new RecordType(Name='yyy', SObjectType='Opportunity');
insert rt;
        String opportunityName= 'yyyy';
            Opportunity o = new Opportunity(
            AccountId=a.Id, 
            Name=opportunityName, 
            StageName='Prospecting', 
            CloseDate=Date.today(),
            Opportunity_Type__c='New',
            LeadSource='yyy',
            RecordTypeId= rt.Id;
            
        insert o;
        system.debug(o.RecordType.Name);

 

KevanKevan
@Munna4manju you miss dml insert on recordtype
RecordType rt = new RecordType(Name='yyy', SObjectType='Opportunity');
insert rt;
        String opportunityName= 'yyyy';
            Opportunity o = new Opportunity(
            AccountId=a.Id, 
            Name=opportunityName, 
            StageName='Prospecting', 
            CloseDate=Date.today(),
            Opportunity_Type__c='New',
            LeadSource='yyy',
            RecordTypeId= rt.Id;
            
        insert o;
        system.debug(o.RecordType.Name);