Play Games

Search This Blog

Thursday, July 2, 2015

SObject row was retrieved via SOQL without querying the requested field

Generally this type of error will occur when we are referring a field which is not present in SOQL query.
For example :
Apex Class:
public class UpdateLeads {
    public void updateLeads() {
        list<lead> leadList = [select id,name from lead ];
        list<lead> leadList1 = new list<lead>();
        for(lead l :leadList ) {  
        l.lastname=l.lastname+'Test';
        leadList1.add(l);
        }
        update leadList1;
        system.debug('swetha'+leadList1);
    }
}

Visualforce Page :
<apex:page controller="UpdateLeads">
<apex:form >
 <apex:commandButton value="Save" action="{!updateLeads}"/>
</apex:form>
</apex:page>

In the above example whenever we click on "save" button we get the above error as shown in the image below
In  apex class above, we are updating  lastname field of lead which is not retrieved or not present in SOQL query.So we got this error.To avoid this type of error,make sure you are retrieving all required fields from SOQL query which are referred in apex class.
change the above query like this
list<lead> leadList = [select id,name,lastname  from lead ];

Enjoy Coding....