Wednesday, August 27, 2014

How to use apex:dynamicComponent in visualforce page to generate DOM elements at run time

Ok so today I am sharing the code for how to generate apex component dynamically. Salesforce has introduced a new feature call as "apex:dynamicComponent", what this does is it will introduce visualforce markup in the page from controller just like a dynamic binging.

To do this use this in the visualforce page:
<apex:dynamicComponent componentValue="{!outPanel}"/>
Now in the class write this:
Public transient Component.Apex.OutputPanel outPanel{get;set;}
Public List<sObject> vNewLst{get;set;}
public void getdynPan(){      
vNewLst = database.query('Select Id,Name from Account limit 100');    
outPanel = new Component.Apex.OutputPanel();   
Component.Apex.DataTable datatable = new Component.Apex.DataTable(var='row');    
datatable.expressions.value='{!vNewLst}';    
list<String> displayFieldLst= new list<String>{'Id','Name'};    
Component.Apex.column clm;   
Component.Apex.OutputText outText;      
for(string s: displayFieldLst){          
clm = new Component.Apex.column(headerValue= '' + s + '');         
outText = new Component.Apex.OutputText();          
outText.expressions.value = '{!row[\'' + s + '\']}';         
clm.childComponents.add( outText );      
datatable.childComponents.add( clm );
}  
outPanel.childComponents.add( datatable );
}
What this code will do it will create a output panel and bind a datatable inside it with Id and Name columns and then display it on the page.

Hope this will help you!!

No comments:

Post a Comment