Dynamic Visualforce Components


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

Example:
VisualForce 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.

Written by 

I am Sakthivel Madesh, a certified Salesforce Advanced Developer & Administrator working on Salesforce Technology since 2011. I am currently working in Techforce Services as Sr. Salesforce Developer. I have worked on multiple technologies Like PHP, Java, Salesforce, I am very passionate about Salesforce and to earn 14x Salesforce Certification. I love Trailhead for learning Salesforce Skill and Become a Trailhead 5x Ranger too. I Love to Learn & Share my Salesforce knowledge to Salesforce Learners/Beginner using My Blog and Salesforce Community.

Leave a Reply