Monday, March 17, 2014

Dynamic Columns in visualforce using Fieldset


Dynamically bind your columns in visual force page block table
All you need is
1- Fieldset on any salesforce standard or Custom Object
2- Apex Class(Controller)
3- Visualforce Page.

1- Fieldset- fieldset is used to dynamically bind the fields in the visualforce page or in apex class. For this first you need to create a field set like --
  1.a- Go to Setup->Customize->Account->FieldSet->New
  1.b- write the Name Account_Fields
  1.c- Now you will get a view like page layout. So you need to drag some field to the Field set Section like you do in Page Layouts.
  1.d- your field set is now created.

2- create an apex class with following code:-

public class AccountFieldSetData {

public list<AggregateResult>lstAccount {get;set;}
public AccountFieldSetData() { 
 String SOQL = ''; 
 SOQL = 'SELECT '; 
 for(Schema.FieldSetMember thisField : this.getFields()) { 
 SOQL += thisField.getFieldPath() + ', '; 
 } 
 SOQL += ' Id from Account limit 50'; 
 lstAccount = database.query(SOQL); 
 } 
 private List<AggregateResult>getFields() {
 return SobjectType.Account.FieldSets.Account_Fields.getFields(); 
 } 
 }

3- Create a visualforce page with following code---


<apex:page controller="Demo_DynamicColumnsInPBTable">
  <apex:sectionHeader title="Dynamic Columns in PageBlock Table"/>
  <apex:form >
      <apex:pageBlock >
          <apex:pageblockTable value="{!lstAccount}" var="account" >
                <apex:repeat value="{! $ObjectType.Account.Fieldsets.Account_Fields}" var="varFieldName">
                    <apex:column value="{! account[varFieldName]}"/>
                </apex:repeat>
            </apex:pageblockTable>
      </apex:pageBlock>
  </apex:form>
</apex:page>


1 comment: