Print this page

Adding Columns Dynamically into PageBlockTable at run time

Knowledge Article Number 000229612
Description

Sample code which adds the Columns dynamically to a PageBlockTable based on the Value you enter in a text box on Visualforce page.

Resolution User-added image
 

This example shows how the Fields can be added at runtime for Account's records dynamically.

There are three custom validation errors in this page:-

1) User can not select duplicate fields.
2) User can not enter wrong Field name.
3) User can not leave the text box blank If click on Add Field Button.


Please note that the below codes are just examples. You need to modify and test it to meet your needs.

VISUALFORCE PAGE:

<apex:page controller="Dynamic_Column_Controller">
<apex:form >
<apex:pageMessages id="ss"></apex:pageMessages>

<apex:pageBlock >
<apex:pageBlockSection >
<apex:pageBlockSectionItem >

<b>Field API Name</b> <apex:inputText id="input1" value="{!FieldName}" />

</apex:pageBlockSectionItem>
</apex:pageBlockSection>

<apex:pageBlockTable id="table1" value="{!accs}" var="rec">

<apex:repeat value="{!SelectedFields}" var="FieldLable"> 
<apex:column value="{!rec[FieldLable]}"/> 
</apex:repeat> 
</apex:pageBlockTable>

<apex:pageBlockButtons >
<apex:commandButton reRender="table1,ss" value="Add Fields" action="{!addFields}"/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>
 

CONTROLLER:

Public Class Dynamic_Column_Controller
{

public List<Account> accs {get;set;}
public List<String> SelectedFields {get; set;} 
public string FieldName {get;set;}
string query;
string fields = '';

public void addFields()
{
try
{

If (FieldName == '' )
{
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,'Please give a Field Name'));
}

SelectedFields.Add(FieldName);

fields = String.Join(SelectedFields, ', ');
fields = fields.RemoveEnd(',');
query = 'Select ' + fields + ' From Account Limit 10';

accs= Database.Query(query);
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM,'Field : ' + FieldName + ' is added in below table'));

}
catch( Exception e )
{

If ( e.getmessage().contains('No such column') )
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Warning,'Field : ' + FieldName + ' is not avaialble on Account'));

If ( e.getmessage().contains('duplicate') )
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,'Field : ' + FieldName + ' is already selected '));

SelectedFields.remove(SelectedFields.size()-1);
}

}

public Dynamic_Column_Controller()
{ 
SelectedFields = New List<String>();

}

}
 
 

 


 




promote demote