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

I have written this controller extension:

public with sharing class PopupController {
    ApexPages.Standardcontroller cont;
    public Request_Change_Reseller__c req{get;set;}

    public PopupController(ApexPages.StandardController cont){
    this.cont = cont;
    req=new Request_Change_Reseller__c();
    req.PartnerUserId__c = ((Lead)cont.getRecord()).Assigned_to_Partner__c;

    }

    public PageReference save(){

    return null;
    }

}

My visualforce page is:

<apex:page standardController="Lead" extensions="PopupController" sidebar="false">
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection columns="1">
  <apex:outputField label="Lead" value="{!Lead.Name}"/>
  <apex:inputField label="Assign To Partner" value="{! req.PartnerUserId__c}" />
<apex:commandButton value="Submit" action="{!save}" />
</apex:pageBlockSection>
</apex:pageBlock>
  </apex:form>
</apex:page>

I created a custom button in the lead layout. When I click on it a new window opens and I get this error:

SObject row was retrieved via SOQL without querying the requested field: Lead.Assigned_to_Partner__c .

Can I not access all fields in a controller extension? Will I have to make a soql query?

Answer

A standardcontroller’s record will only contain the fields referenced in the visualforce page you’re using it on. The standard controller addFields(List) method (docs) allows you to extend this to the fields you need in your apex code.

cont.addFields(new List<String>{'Assigned_to_Partner__c'});

Set this as the 2nd line in your constructor.

Attribution
Source : Link , Question Author : user133421 , Answer Author : Srilakshmi B S

Leave a Comment