Home Dynamic Visualforce Components Example

Dynamic Visualforce Components Example:

Example of generate a dynamic input form for Account object

VisualForce Page:

<apex:page standardController="Account" extensions="DynamicAccountForm">
<!-- Create section header dynamically -->
<apex:dynamicComponent componentValue="{!SectionHeader}"/>
<apex:form >
<!-- Create dynamic input form for account object -->
<apex:dynamicComponent componentValue="{!ActionForm}"/>
</apex:form>
</apex:page>

Apex Class:

public with sharing class DynamicAccountForm
{
    public DynamicAccountForm(Apexpages.standardController ctlr)
    {
        //constructor
    }  
    //Create a page block dynamically
    public Component.Apex.PageBlock getActionForm()
    {
        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 = 'First 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 getSectionHeader()
    {
        Component.Apex.SectionHeader sh = new Component.Apex.SectionHeader();
        sh.title = 'Create Account';
        return sh;
    }
}

Leave a Comment