Wednesday, August 22, 2012

Examples of Dynamic Visualforce Components

Dynamic Visualforce Components

Using Dynamic Visualforce components, we can dynamically generate HTML values like apextable, PageBlock, PageHeader, SectionHeader, etc,..

Example:

VisualForce Page:

<apex:page standardController="Account" extensions="DynamicForm">
<!-- 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 DynamicInputForm
{
    public DynamicInputForm(Apexpages.standardController ctlr)
    {
        //constructor code
    }
  
    //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 = '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;
    }
}


Note: Dynamic Visualforce components are not intended to be the primary way to create new Visualforce pages in your organization. Existing Visualforce pages shouldn't be rewritten in a dynamic manner and, for most use cases, standard Visualforce components are acceptable and preferred. You should only use dynamic Visualforce components when the page must adapt itself to user state or actions in ways that can't be elegantly coded into static markup.