Salesforce VF Page: Retrieve Field without SOQL
I was working on a Salesforce project which involves a lot of VisualForce page customisation. During the development, I encountered a very common error “SObject row was retrieved via SOQL without querying the requested field”, but it took me awhile to find out the root cause.
I wrote a VisualForce with Standard Controller and an Extension class. Below is the code:
Extension Class:
public class myControllerExtension { public extendedobject__Extended_Object__c myObj {set; get;} public myControllerExtension(ApexPages.StandardController stdController) { this.myObj = (extendedobject__Extended_Object__c)stdController.getRecord(); } }
VisualForce Page:
As you can see that I only display the record Name in the VisualForce page, and I assumed that Salesforce will retrieve the value for me automatically according the Id that I passed in the url. However, this is not the case. After doing some research, I found two methods to solve this issue:
Option 1
Specify the list of fields that I want to retrieve and set it to the standardController
public myControllerExtension(ApexPages.StandardController stdController) { List fields = new List{'Name'}; stdController.addFields(fields); this.myObj = (extendedobject__Extended_Object__c)stdController.getRecord(); }
Option 2
Change the variable in the VisualForce page to use the object name instead of the variable that I specified in the Extension class