Using field sets to display data in VF page


This is one of the first methods to display dynamic columns/fields on a visualforce page as specified in my previous blogpost.

As you might be aware that almost all standard/custom objects supports field sets. Field sets are introduced to give flexibility to a user/Admin to change the fields that are being displayed in a visualforce page by themselves, without touching the code. This also helps in case you are offering a vf page as part of managed package. Whoever install the package, can control fields-to-be-displayed using field sets used in the vf page.

In the example below, i am going to create a vf page on Account object.
Here is all you need for this:

1) Field set on Account. I will call it VFPAGECOLUMNS. you can create it by going to set->Customize->Account->FieldSets


2) Access this field set from your VF page by using. In my case i am using this inside <Apex:repeat> to iterate each field in the field set. 

{!$ObjectType.Account.fieldSets.VFPageColumns}

Here is the complete code:

<apex:page standardcontroller="Account">
    <apex:form>
    <apex:pageblock title="Dynamic columns in Visualforce Page with FieldSet">
        <apex:pageblocksection>
            <apex:repeat value="{!$ObjectType.Account.fieldSets.VFPageColumns}" var="accField">
                    <apex:inputfield value="{!Account[accField]}">
                    </apex:inputfield></apex:repeat>
            </apex:pageblocksection>
        </apex:pageblock>
    </apex:form>

</apex:page>


And the output looks like following. Also. you can also set fields to required in the layout from the field set by double clicking on any field and set it to Required

Showing dynamic fields/columns in VisualForce Page

A lot of times, we choose visualforce pages to override standard view/edit views in salesforce. But one of the drawbacks in choosing this approach is that the client has to rely on a developer to make any changes in the field being displayed on the page or to add a new field in the layout of the visualforce page. 

There are several approach by which we can go for visualforce pages with still having the flexibility for the client or admin to change the fields by themselves without even changing the code. Here are few methods:

1) Using Field Sets
2) Using Reports
3) Using ListViews

Share in comments if you are aware of any other methods to achieve the same.