[SalesForce] How do we dynamically add columns in a datatable

I am trying to build a VF page which dynamically displays the datatable. The fields to be displayed are not known, they need to taken from a custom setting.

Here is what i am trying to achieve

I have a custom setting which has field names(API names) of columns that need to be displayed in the data table

I also have a list of a quotelineitem which also uses this custom setting to get the records. The issue i am facing is how do we display the columns in datatable as we would only know the field name at run time.

In the code below to display account name i would need to specify <apex:outputText value="{!account.name}"/> in the VF page, but since i really dont know which fields would be displayed is there a way we can dynamically populate the field names.

I am not stuck with datatable, i am open to any other way to dynamically display the fields

            <apex:facet name="header">Name</apex:facet>

        <apex:facet name="footer">column footer</apex:facet>

        <apex:outputText value="{!account.name}"/>

   </apex:column>

Best Answer

Visualforce allows you to use brackets ([]) that treats data like a map. For sObjects in a visualforce page they're treated like a map of field values with api names for keys. So you just need to loop over the api names from your custom setting. The example below uses a page block, but you can use pretty much any output structure you want.

Example

<apex:pageBlock>
  <apex:pageBlockTable value="{!records}" var="record">
    <apex:repeat value="{!fieldAPINames}" var="fieldAPIName">
      <apex:column value="{!record[fieldAPIName]}"/>
    </apex:repeat>
  </apex:pageBlockTable>
</apex:pageBlock>