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.
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.
<apex:outputText value="{!Condition__c.Criterion__c}" rendered="false"/>
Happy Coding 🙂
4 comments
Skip to comment form
Thanks.
For generic methods that you want to work on whichever fields *were* retrieved, is there a way to determine if a field was retrieved or not before referencing it and avoid the error that way?
Quick question. When editing the accounthierarchy visualforce component, I’m trying to change the type and industry field (see code below). When I swap out .type and .industry with the custom fields we want, I get the error above. How do I fix that? I assume I need to add a customer controller somewhere?
Thank You