[SalesForce] How to dynamically retrieve FieldSet fields using Apex

I'm following the following tutorial:

Using field-sets with visualforce

I'd like to retrieve and populate a table's columns dynamically based on the fieldset. I would like to do this by somehow using the field set name to change which fields are retrieved.

I have the following code, here is my VF page:

<apex:page controller="FieldSetTest">
    <apex:form >
        <apex:repeat value="{!currentFieldSet}"  var="C">
            <span  class="label" style="align:right"> {!C.label}  </span>  
            <apex:inputField value="{!newCase[C.fieldPath]}" /> 
        </apex:repeat>
    </apex:form>
</apex:page>

Here is my apex:

public class FieldSetTest {

    public Case newCase { get; set; } {newCase = new Case();}
    public List<Schema.FieldSetMember> currentFieldSet {get;set;} {currentFieldSet = new List<Schema.FieldSetMember>();}

    public void FieldSetTest() {
        currentFieldSet = readFieldSet('PendingHelpdeskCase','Case');
    }

    public List<Schema.FieldSetMember> readFieldSet(String fieldSetName, String ObjectName) {
        Map<String, Schema.SObjectType> GlobalDescribeMap = Schema.getGlobalDescribe();
        Schema.SObjectType SObjectTypeObj = GlobalDescribeMap.get(ObjectName);
        Schema.DescribeSObjectResult DescribeSObjectResultObj = SObjectTypeObj.getDescribe();
        Schema.FieldSet fieldSetObj = DescribeSObjectResultObj.FieldSets.getMap().get(fieldSetName);
        return fieldSetObj.getFields();
    }
}

I would like to use the above line:

currentFieldSet = readFieldSet('PendingHelpdeskCase','Case');

To pass in the field set name and depending on the field set, display different fields in my apex:repeat component. Right now it does not populate the page with anything, can anybody let me know what I'm doing wrong?

Best Answer

It is clear that you need to call the action method FieldSetTest, because this is not a constructor, so not getting automatically called.

Please use the below code, and it will call your method on page load, and have the things populated on load of the page.

<apex:page controller="FieldSetTest" action="{!FieldSetTest}">    

Hope this helps.

Related Topic