Hello friends, In this tutorial, I am providing a working example that helps you to create visualforce component such as SectionHeader, PageblockTable, InputText dynamically using apex class.

After completing this tutorial you’ll able to:
  • Create a Visualforce component dynamically.
So let’s begin,

Step 1: Login to your Salesforce Org. and open developer console.

Step 2: Navigate to File | New | Apex Class and create an apex controller called AccountHandler and replace the following code.

AccountHandler.apxc
 public class AccountHandler
 {
    public AccountHandler(ApexPages.StandardController controller) 
    {

    }   
    
    //Dynamic creation of Section Header
    public Component.Apex.SectionHeader getsecHead()
    {
        Component.Apex.SectionHeader sh = new Component.Apex.SectionHeader();
        sh.title = 'Create Account';
        return sh;
    }  
      
    //Dynamic creation of pageBlock
    public Component.Apex.PageBlock getformSample()
    {
        Component.Apex.PageBlock pageBlock = new Component.Apex.PageBlock();
      
        //Dynamic creation of inputField
        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';
        
        //Dynamic creation of CommandButton
        Component.Apex.CommandButton save = new Component.Apex.CommandButton();
        save.value = 'Save';
        save.expressions.action = '{!Save}';


        pageBlock.childComponents.add(label);
        pageBlock.childComponents.add(name);
        pageBlock.childComponents.add(save);
        return pageBlock;
    }
    
 }
Step 3: Navigate to File | New | Visualforce Page and create a new Visualforce Page called DynamicVFComponent and replace the following markup.

DynamicVFComponent .vfp
 <apex:page standardController="Account" extensions="AccountHandler">
    <!-- Dynamic creation of Section Header -->
    <apex:dynamicComponent componentValue="{!secHead}"/>
    
    <apex:form >
        <!-- Dynamic creation of pageBlock -->
        <apex:dynamicComponent componentValue="{!formSample}"/>
    </apex:form> 
 </apex:page>
Output:

See also:

Conclusion:
Hope you like this tutorial, for any query or suggestions please feel free to comment.
Thank you.