Creating and using Custom Component in Visualforce Page

|
| By Webner

Custom Component in Visualforce Page

Custom Component is very useful in the Salesforce. Sometimes, in the visualforce page, we need the same block of code again and again. For this, we can create VisualForce Component which will contain the common code which is used again and again. After creating the Custom Component, we just have to add that component to the Visualforce page for using it.

Basic Syntax:-

1. Creation and usage of component:-

a. Creation

<apex:component controller=”controllerName”>
//common code that you want to reuse
</apex:component>

b. Usage

 <apex:page>
<c:componentName></c:componentName>
</apex:page>

2. Passing parameters to the component (when using in the Visualforce Page):-

a. Creation of Component (add Attribute)

<apex:component controller=”controllerName”>
<apex:attribute name=”variableName” description=”is required” type=”String”>
//common code that you want to reuse
</apex:component>

b.Passing value to the attribute of the component

<apex:page>
<c:controllerName variableName="Testing"></c:controllerName>
</apex:page>

Example:-

VisualForce Component:-

<apex:component controller="FirstComponent">
<apex:attribute name="componentValue" description="This is the description for the component" type="String"/>
<apex:outputText value="{!componentValue}"></apex:outputText>
</apex:component>

VisualForce Controller:-

public with sharing class FirstComponent {
    public String componentValue { get; set; }
}
VisualForce Page :-

<apex:page>
 	<c:firstcomponent componentValue="Testing"></c:firstcomponent>
</apex:page>

Leave a Reply

Your email address will not be published. Required fields are marked *