[SalesForce] SObject row was retrieved via SOQL without querying the requested field: Opportunity.Unsolicited_Bid__c:

I get the following error in my SalesForce app:

Error:Apex trigger UpdateOpportunity caused an unexpected exception, contact your administrator: UpdateOpportunity: execution of BeforeUpdate caused by: System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Opportunity.Unsolicited_Bid__c: Class.OpportunityMethods.updateOppCompetitor: line 11, column 1

I see there are a lot of similar questions, but I've tried their solutions and still can't get this query to work correctly.

Here is the trigger I have:

trigger UpdateOpportunity on Opportunity (before insert, before update){

    Opportunity[] oppQuery = [SELECT ID, RecordType.Name, StageName, Win_Reason__c FROM Opportunity WHERE ID IN :Trigger.new];  

    for(Opportunity opp : oppQuery){

        if(opp.RecordType.Name == 'SGI Opportunity' && opp.StageName != 'Lead 0%'){

            OpportunityMethods.updateOppCompetitor(opp);  
    }
}

And here's the class I use in the trigger that has Win_Reason__c, the field in question.

public Class OpportunityMethods {

public static void updateOppCompetitor(Opportunity opp){

    if(opp.Win_Reason__c == 'No Competition/Sole Source'){

    System.debug('THIS WORKED');

        opp.Competitor_s__c = 'No Competitor/Sole Source'; 
    }
    if(opp.Unsolicited_Bid__c == 'Yes'){


    System.debug('THIS WORKED');


        opp.Competitor_s__c = 'No Competitor/Sole Source';
    } 
}

}

Any clue what else I need to add to the SOQL query to make it run correctly?

Thanks in advance!

Best Answer

Please add the column Unsolicited_Bid__c to your oppQuery.

That is what the exception System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Opportunity.Unsolicited_Bid__ was trying to relay, that there was an attempt to get/set a field on an sobject from a query that originally did not query that field.

As an aside, do you have a specific reason for re-querying the opportunities inside the trigger? I believe you can reference and loop through Trigger.new and reference any of the opportunity fields and likely avoided this exception initially:

for(Opportunity opp : Trigger.new){
    if(opp.RecordType.Name == 'SGI Opportunity' && opp.StageName != 'Lead 0%'){
        OpportunityMethods.updateOppCompetitor(opp);  
    }
}
Related Topic