Apr 12

Print this Post

Custom Visualforce Component example

Custom Visualforce Component example

Custom visualforce components are very useful. In our projects, many times we develop codes which are required again and again. So instead of repeating same code again and again, we can create visualforce component. Then we can use visualforce component in every place where we need that particular piece of code. In other words, custom visualforce component allows us to create reusable component.

All custom visualforce component definitions must be wrapped inside a single <apex:component > tag.

We can also use <apex:attribute> tag to use customize the component so that custom component can be used in different manners depending on value of different attributes. It helps us in creating reusable generic component and also saves time and number of lines we write in apex and visualforce page.

In the example below, we will learn to create very basic custom visualforce component.

Click for Demo

Custom Visualforce Component example

First we will create visualforce component. Go to Setup -> Develop -> Components -> then write component name. In our case component name is ‘myComponent’.

Component Code:

<apex:component >
    <apex:attribute name="textValue" description="This is the value for the component" type="String" required="true"/>
    <apex:attribute name="textColor" description="This is color for the border." type="String" required="true"/>
    <apex:outputText value="{!textValue}" style="color:{!textColor};"/>

This component is creating two attributes using <apex:attribute> tag. First attribute is deciding what text text should be displayed and second attribute is deciding color of text. We can use any number of attribute in component. Component can also have controller which helps in more customizable component.

Now we need to use this component. We can use component in visualforce page using <c:componentName>.

Visualforce Code:

<apex:page tabStyle="Account"> 
    <apex:pageBlock >
        <apex:pageBlockSection title="myComponent Test" collapsible="false">
            <c:myComponent textValue="This Text is blue" textColor="blue" />
            <c:myComponent textValue="But this is red" textColor="red" />

Permanent link to this article: http://www.sfdcpoint.com/salesforce/custom-visualforce-component-example/

  • Amit

    simple and nice description for new guys

  • Arora

    Can we reuse a component which isnot global.? Actually I want to use a component which is present in the package, I downloaded from AppExchange. What should I do?

    • If component is part of managed package and it is not global. Then we can not use it in our custom code.

  • ప్రవీణ్ నరహరిశెట్టి

    wrthy information!!!