0

Site extenion class:

public with sharing class siteExtension {
    private ApexPages.StandardController controller;

    private Set<String> SiteFields = new Set<String>();

    public siteExtension (ApexPages.StandardController controller) {
        this.controller = controller;
        Map<String, Schema.SobjectField> fields = 
        Schema.SobjectType.Site__c.fields.getMap();

        for (String s : fields.keySet()) {
        // Only include accessible fields 
            if (fields.get(s).getDescribe().isAccessible() && 
                fields.get(s).getDescribe().isCustom()) {
                    SiteFields.add(s);
            }
        }
    }

    public  List<String> availableFields {
        get {
            controller.reset(); 
            controller.addFields(new List<String>(SiteFields));
                return new List<String>(SiteFields);
        }
    }
}

VF Page:

<apex:pageBlock title="{!Site__c.Name}">
    <apex:repeat value="{!availableFields}" var="field">
        <h2><apex:outputText 
             value="{!$ObjectType['Site__c'].Fields[field].Label}"/></h2>
        <br/>
        <apex:outputText value="{!Site__c[field]}" /><br/><br/>

    </apex:repeat>
</apex:pageBlock>

Why do I get this error:

SObject row was retrieved via SOQL without querying the requested field: Site__c.Home_Content_Body__c

I followed the tutorial from https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_dynamic_vf_sample_custom.htm

1 Answer 1

3

The standard controller by default will query for all fields referenced directly on the page. However, if you reference them dynamically instead, you need to explicitly add them in your constructor. Note that this operation cannot be performed in a test.

I would reorganize your code slightly as well:

public List<String> availableFields { get; private set; }
public siteExtension (ApexPages.StandardController controller)
{
    availableFields = new List<String>();
    // populate via existing logic
    if (!Test.isRunningTest()) controller.addFields(availableFields);
}
1
  • Just an extra note that the !Test.isRunningTest() is because you cannot call addFields when you created the ApexPages.StandardController yourself. If you plan to re-use this controller internally at all you will need to instead overload the constructor or come up with a similar pattern where you know that you are constructing it yourself as opposed to the Visualforce engine constructing it.
    – dsharrison
    Apr 25, 2017 at 18:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .