function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
James L.James L. 

StandardSetController.AddFields not working

Here's my sample code.

 

AddFields, if located in constructor, works; if not, will cause exception:

System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: 

 

<apex:page standardController="account" extensions="LearnVFaddFields" recordSetVar="accounts">
   <apex:form >
   <apex:commandButton value="Change" action="{!changeFields}"/>
   <apex:pageblock >
       <apex:pageblockTable value="{!accounts}" var="acct">
           <apex:repeat value="{!fields}" var="f">
               <apex:column value="{!acct[f]}"/>
           </apex:repeat>
       </apex:pageblockTable>
   </apex:pageblock>
   </apex:form>
</apex:page>



public with sharing class LearnVFaddFields {
    ApexPages.StandardSetController controller;

    public List <String> fields {
        get;
        private set;
    }

    public LearnVFaddFields(ApexPages.StandardSetController controller) {
        List <String> fields = new List <String>{'Name', 'Rating'};
        this.controller = controller;
        updateRows(fields);
    }
    
    private void updateRows(List <String> fields) {
        this.fields = fields;
        controller.reset(); 
        controller.AddFields(fields);        
    }
    
    public PageReference changeFields() {
        List <String> fields = new List <String>{'Phone', 'type'};
        updateRows(fields);
        return null;
    }
}

 


Best Answer chosen by Admin (Salesforce Developers) 
Damien_Damien_

I worked with this awhile back, and as I remember its only allowed in the constructor.