Thursday 13 April 2017

SObject row was retrieved via SOQL without querying the requested field in Controller

I just struck with one of the issue when developing something in visualforce page.

The problem is when I load the visualforce page am seeing this below error

Error : SObject row was retrieved via SOQL without querying the requested field


I was trying to fetch the field in controller like below,

Public class caseController{

     public Case cas {get; set;}
     private ApexPages.StandardController controller {get; set;}
     public string caseOwnId{get;set;}

     public caseController(ApexPages.StandardController controller) {
        this.controller = controller;
        cas = (Case) controller.getRecord();
        string caseOwnId = cas.OwnerId;
}

When I use the string field caseOwnId in visualforce page to display the owner id, it is saying that 'SObject row was retrieved via SOQL without querying the requested field'. Isn't this weird?.

Usually, we will see this error if we missed the field while querying. right?.

After some time I found the solution for this as well. Ofcourse the solution is very new to me.

The solution is, we can add the field API name in the controller itself. see below,

controller.addFields(new List<String>{'OwnerId'});

We have method called addFields in the controller. By using that, we just need to add the api name of the field to the list. That's it. So, the full constructor would be,


Public class caseController{

     public Case cas {get; set;}
     private ApexPages.StandardController controller {get; set;}
     public string caseOwnId{get;set;}

     public caseController(ApexPages.StandardController controller) {
        this.controller = controller;
        controller.addFields(new List<String>{'OwnerId'});
        cas = (Case) controller.getRecord();
        string caseOwnId = cas.OwnerId;
}