Wednesday, May 16, 2012

Dynamic Visualforce Components Explained


Some or the other time you might have faced a challenge of dynamically generating input fields. Most of the time we sticked to dynamic HTML and embed that in our VF page to fulfil our needs.

But now, Salesforce has introduced the new Dynamic visualforce components which means you no longer will be dependent on dynamic HTML for most of your needs.

Here is a sample which shows you how to generate a dynamic input form for Account object.

Page
<apex:page standardController="Account" extensions="DynamicInputForm">
<!-- Create section header dynamically -->
<apex:dynamicComponent componentValue="{!SH}"/>
<apex:form >
<!-- Create dynamic input form for account object -->
<apex:dynamicComponent componentValue="{!ActForm}"/>
</apex:form>
</apex:page>

Class
public with sharing class DynamicInputForm
{
    public DynamicInputForm(Apexpages.standardController ctlr)
    {
        //constructor code goes here
    }

  
    //Create a page block dynamically
    public Component.Apex.PageBlock getActForm()
    {
        Component.Apex.PageBlock pb = new Component.Apex.PageBlock();
      
        //creating an input field dynamically
        Component.Apex.InputField name = new Component.Apex.InputField();
        name.expressions.value = '{!Account.Name}';
        name.id = 'name';
        Component.Apex.OutputLabel label = new Component.Apex.OutputLabel();
        label.value = 'Name';
        label.for = 'name';
        //Use the above block to create other input fields
      
        Component.Apex.CommandButton save = new Component.Apex.CommandButton();
        save.value = 'Save';
        save.expressions.action = '{!Save}';


        pb.childComponents.add(label);
        pb.childComponents.add(name);
        pb.childComponents.add(save);
        return pb;
    }

  
    //create section header dynamically
    public Component.Apex.SectionHeader getSH()
    {
        Component.Apex.SectionHeader sh = new Component.Apex.SectionHeader();
        sh.title = 'Create Account';
        return sh;
    }
}
Updated Visualforce developer guide covers this topic.

No comments:

Post a Comment