[SalesForce] SObject row was retrieved via SOQL > without querying the requested field

I am working on a trigger that creates one custom object record (Recipe Sheet) for each Opportunity Line Item associated to an Opportunity. Everything is working correctly except I need to set the Record Type of these Recipe Sheet's.

I tried creating a text field on the product table to store the appropriate Record Type Id for each Product thinking I could just query that and set the Record Type Id the same was as any other field. However I receive this error:

"Error:Apex trigger NewRecipeSheets caused an unexpected exception,
contact your administrator: NewRecipeSheets: execution of AfterUpdate
caused by: System.SObjectException: SObject row was retrieved via SOQL
without querying the requested field: Product2.Record_Type_ID__c:
Trigger.NewRecipeSheets: line 21, column 1"

How can I set the Record Type Ids based on the Products added via this trigger?

trigger NewRecipeSheets on Opportunity (after update){

    List<Recipe_Sheet__c> RecipeList =new List<Recipe_Sheet__c>();
    List<Opportunitylineitem> opplinitemlist =new List<Opportunitylineitem>();
    List<Opportunity> Opportunitylist =new List<Opportunity>();

    for(Opportunity opp :trigger.new){
        if(opp.Stagename=='Closed Won'&&opp.Create_Recipe_Sheet_s__c==True){       
        Opplinitemlist =[select Id,PricebookEntry.Product2.Name,Product2.Do_Not_Discount__c,Product2.Record_Type_ID__c,Total_Drop__c,Finish_s__c,Notes__c, For_Vaulted_Ceiling__c,PricebookEntry.Product2.id from Opportunitylineitem where Opportunityid =: opp.id AND Product2.Do_Not_Discount__c=False];
        Opportunitylist  =[Select Accountid from Opportunity where Id =: opp.id];

        for(Opportunitylineitem Opplist :opplinitemlist ){
        Recipe_Sheet__c rec =new Recipe_Sheet__c();
        rec.Opportunity__c =Opportunitylist[0].Id;
        rec.product__c=opplist.PricebookEntry.Product2.Id;
        rec.Name=opplist.PricebookEntry.Product2.Name;
        rec.For_Vaulted_Ceiling__c=opplist.For_Vaulted_Ceiling__c;
        rec.Finish_s__c=opplist.Finish_s__c;
        rec.Notes__c=opplist.Notes__c;
        rec.Total_Drop__c=opplist.Total_Drop__c;
        rec.RecordTypeID=opplist.PricebookEntry.Product2.Record_Type_ID__c;
        RecipeList.add(rec);
        }
        insert RecipeList;
        } 
        }  

Best Answer

Change this:

rec.RecordTypeID=opplist.PricebookEntry.Product2.Record_Type_ID__c;

To this:

rec.RecordTypeID=opplist.Product2.Record_Type_ID__c;
Related Topic