Salesforce Menu

Introduction to Visualforce Components

Visualforce components are reusable visualforce parts of code which can be used anywhere in our visualforce markup.

There are two types of visualforce components :

  1. Standard Visualforce Components : These are pre-built components which can be directly used in the visualforce markup, for example the component can be used to display related lists for any object.
  2. Custom Visualforce Components : These are custom built components which can be used in any visualforce pages.

Custom Component Syntax

In order to create a custom visualforce component, you need to go to Setup -> Search for ‘Visualforce Components’.

Click on New, and name your component ‘MyFirstVFComponent’. Paste this code and save your component :

<apex:component >
    <apex:attribute type="String" name="textToShow" default="My First VF Component" description="text attribute"/> 

So visualforce components have <apex:attributes> which are essentially like variables to be used inside your visualforce component. We can pass values to these attributes and can also specify default values to these. The apex attributes support multiple types (reference :

Using an Visualforce Component in a Visualforce Page

Let’s define a new visualforce page and use the above defined visualforce component inside it. We can use the component like this :

<apex:page sidebar="false" showHeader="false">

Here c represents the default namespace of the visualforce components.

Output :

The visualforce component prints out the default value of the attribute. We can also pass in the value to this attribute.

<apex:page sidebar="false" showHeader="false">
  <c:MyFirstVFComponent textToShow="Salesforce Drillers"/>

Output :

Subscribe Now