Using Dynamic Component in VisualForce Page

For some cases it might be useful to build component for visualforce page dynamically inside the code.

Take a look at the following code example of generating PageBlockTable inside the code.


public class vf_DynamicComponentExmp {  

 transient public Component.Apex.PageBlockTable table {get;set;}  

 //list of record to display  
 public list<Case> caseLst {get; set;}  

 //fields and labels to display in the page block table  
 public list<String> displayFieldLst= new list<String>{'CaseNumber', 'Subject', 'Priority', 'Status', 'ContactID'};  
 public list<String> labelFieldLst= new list<String>{'Case Number', 'Subject', 'Priority', 'Status', 'Contact'};  

 public vf_DynamicComponentExmp() {  
  String dynamicSQL='SELECT id ';  
  for(String field : displayFieldLst) {
   dynamicSQL+=', ' + field;  
  }

  dynamicSQL+=' FROM Case';  

  caseLst=Database.query(dynamicSQL);  

  table = new Component.Apex.PageBlockTable(var='rec');  
  table.expressions.value='{!caseLst}';  
    
  //add the field  
  Component.Apex.Column column;  
  Component.Apex.InputField inputField;  

  for(Integer index=0;index<displayFieldLst.size();index++) {  
   column = new Component.Apex.Column(headerValue= '' + labelFieldLst.get(index) + '');  
   inputField = new Component.Apex.InputField();  
   inputField.expressions.value = '{!rec.' + displayFieldLst.get(index) + '}';  
   column.childComponents.add(inputField);  
   table.childComponents.add(column);  
  }  
 }  

 public PageReference saveData() {  
  try {   
   update caseLst;   
  }   
  catch(Exception e) {   
   ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error while saving ' + e));   
  }   
  return ApexPages.currentPage();   
 }  
}  

In the page we reference it by:
<apex:dynamicComponent componentValue="{!table}"/>


<apex:page controller="vf_DynamicComponentExmp">  
 <apex:pageMessages id="errors" escape="false" />   
 <apex:form >  
  <apex:pageBlock >  
   <apex:pageBlockButtons location="top" id="buttons">   
    <apex:commandButton id="Save" value="Save" action="{!saveData}" />   
   </apex:pageBlockButtons>  

   <apex:dynamicComponent componentValue="{!table}"/>   
  </apex:pageBlock>   
 </apex:form>  
</apex:page>  



The result:




No comments:

Post a Comment

Retire of Permission on Profiles

If you are working as a Salesforce admin/developer you've probably heard somewhere that Salesforce is planning to make a significant cha...