salesforce
  1. salesforce-apex-component

apex:Component

In Visualforce, apex:component is a tag that defines a reusable component that can be used throughout an application. The apex:component tag allows developers to create reusable sections of code that can be included in multiple Visualforce pages.

Syntax

The basic syntax for apex:component is as follows:

<apex:component [access="global"] [description="description"]
         [extends="componentName"] [implements="interfaceName1, [interfaceName2], ...")]
         [published="true | false"] [allowDML="true | false"] [allowSObjectCRUD="true | false"] >
    <body>
        <!-- Component code here -->
    </body>
</apex:component>

Example

Here's an example of an apex:component that renders a custom button with a configurable label:

<apex:component access="global">
    <apex:attribute name="buttonLabel" type="String" required="true" description="The label for the custom button."/>
    <a class="btn">{!buttonLabel}</a>
</apex:component>

This component can then be included in any Visualforce page using the following syntax:

<c:customButton buttonLabel="Submit"/>

Explanation

In the example above, the apex:component tag defines a custom component called customButton. The component takes a single attribute called buttonLabel, which is a required string attribute that defines the label for the custom button. The body tag contains the code for the custom button, which uses the buttonLabel attribute to set the label of the button.

When the component is included in a Visualforce page, the buttonLabel attribute is passed to the component as a parameter. The {!buttonLabel} expression in the component code then inserts the label into the button.

Use

apex:component is useful when you need to reuse the same code throughout an application. By defining a custom component, developers can write code once and use it in multiple Visualforce pages, reducing duplication and improving maintainability.

Important Points

  • Attributes passed to the component can be of any type, and can be required or optional.
  • Components can extend another Visualforce component using the extends attribute.
  • Components can implement one or more Visualforce interfaces using the implements attribute.
  • Components can be published for use in managed packages using the published attribute.
  • The allowDML and allowSObjectCRUD attributes control whether the component can perform DML operations or access sObject data.

Summary

apex:component is a powerful feature of Visualforce that allows developers to create reusable components that can be included in multiple pages. Components can take attributes of any type and can be extended or implemented just like regular Visualforce pages. Using apex:component improves code reuse and maintainability in Visualforce applications.

Published on: