Saturday 1 December 2012

Dynamic Creation of VF components from Apex


We can create almost all VF components dynamically through controller.

Example:

// this is the controller which is used to develop the dynamic components.
// it's an example, in which several components are being created. you can try it one by one.

public class testController{
// this function asigns a panel bar to the outputPanel.
    public Component.Apex.OutputPanel getDynamicPanel() {
        // creates a outputPanel reference
        Component.Apex.OutputPanel dynOutputPanel = new Component.Apex.OutputPanel();
        Component.Apex.PanelBar dynPanelBar = getPanelBar();

        // adding a panel bar as a child component of outputPanel
        dynOutputPanel.childComponents.add(dynPanelBar);
        return dynOutputPanel;
    }

    private Component.Apex.PanelBar getPanelBar(){
        // creates a panelBar reference
        Component.Apex.PanelBar dynPanelBar = new Component.Apex.PanelBar();
        Component.Apex.PanelBarItem dynPanelBarItem = getPanelBarItem();

        // adding a panel bar Item as a child component of panelBar
        dynPanelBar.childComponents.add(dynPanelBarItem);
        return dynPanelBar;    
    }

    private Component.Apex.PanelBarItem getPanelBarItem(){
        // creates a panelBarItem reference
        Component.Apex.PanelBarItem dynPanelBarItem = new Component.Apex.PanelBarItem();
     
        // adding a pageBlock as a child component of panelBarItem
        dynPanelBarItem.childComponents.add(dynPageBlock);
        return dynPanelBarItem;      
    }
}

// This is the visual force page for the above controller

<apex:page>
<apex:form>
<apex:dynamicComponent componentValue="{!dynamicPanel}"/>
</apex:form>
</apex:page>

Notes:

1. We can add multiple dynamicComponent in a visualforce page.

2. Dynamic Component tag is the only place where we can add dynamically generated component.

3. Attributes can also be assigned to the components.

2 comments:

  1. Hi, I would like to apply style for command button attribute title which acts as a tooltip for commandbutton like by changing the color,keeping an image or applying font style for the tittle attribute of a commandbutton. Kindly tell me how to do that

    ReplyDelete
  2. Hi Sampath,

    If I understand you correctly then you want to apply some styling to your command button. For that you can use CSS for your button. For ex:



    .cmdbtn{
    font-size: xxx;
    font-family:xxx;
    background:xxx;
    }

    ReplyDelete