SObject row was retrieved via SOQL without querying the requested field

SObject row was retrieved via SOQL without querying the requested field

SObject row was retrieved via SOQL without querying the requested field is very common error in apex. As name of error suggest, this error occurs when we try to use some field of an object instance which is not queried.

There can be two possible reason for this error.

  1. When we try to use a field in Apex or visualforce which is not queried. For example:

    List accList = [SELECT Id, Name FROM Account WHERE Name like ='%test'];
    for(Account acc : accList){
    System.debug('Account industry is'+ acc.Industry);
    }
    

    Or if we try to use it in visualforce page like this

    <apex:outputField value="{!acc.Industry}"/>
    

Solution for this type of problem is very easy we can simply add Industry field in SOQL query like this:

List accList = [SELECT Id, Name FROM Account WHERE Name like =’%test’];

But sometime our visualforce page or apex class is very complex and we don’t know which field will be used.  In SOQL there is no standard way of querying all fields of object. In that case we can query all fields from SOQL using dynamic query.  For details refer to below link:

Dynamic SOQL query to fetch all fields in Salesforce

2.  The error “SObject row was retrieved via SOQL without querying the requested field” can occur when accessing a Visualforce page with a standard controller and a custom controller extension.

When a standard controller queries an object for a Visualforce page, it only retrieves the fields from the object that are referenced in the page.
This improves efficiency by not retrieving fields that are not needed by the Visualforce page.

When a custom controller references a field that is not included in the page, the field data is not available, and the error occurs.

Workaround:

  • You can add a SOQL query to the custom controller that queries the missing fields
  • You can add a hidden reference to the field in the Visualforce page.
For example:
<apex:outputText value="{!Condition__c.Criterion__c}" rendered="false"/>

Official Salesforce link

Happy Coding 🙂

 

Permanent link to this article: http://www.sfdcpoint.com/salesforce/sobject-row-was-retrieved-via-soql-without-querying-the-requested-field/