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
Anu Raj.ax1269Anu Raj.ax1269 

How do we dynamically add columns in a datatable

Hi, 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 chosen by Admin (Salesforce Developers) 
Bhawani SharmaBhawani Sharma
Create a list of the field names from custom setting. Use this list in a repeat for drawing clloumns. Like is Fields are stored in listFields variable:

<apex:repeat value="{!records}" var="item">
<apex:repeat value="{!listFields}" var="fName">
<td>{!item[fName]}</td>
</apex:repeat>
</apex:repeat>

All Answers

Bhawani SharmaBhawani Sharma
Create a list of the field names from custom setting. Use this list in a repeat for drawing clloumns. Like is Fields are stored in listFields variable:

<apex:repeat value="{!records}" var="item">
<apex:repeat value="{!listFields}" var="fName">
<td>{!item[fName]}</td>
</apex:repeat>
</apex:repeat>

This was selected as the best answer
Bhawani SharmaBhawani Sharma
One more thing is, you can use field set to keep your columns dynamic.