The <apex:attribute>
component is used within custom components to define attributes (parameters) that can be passed from a Visualforce page to that component.
It helps make custom components flexible and reusable by accepting dynamic values.
Syntax
xmlCopyEdit<apex:component>
<apex:attribute name="recordName" type="String" description="Name of the record" required="true"/>
Hello, {!recordName}
</apex:component>
Key Attributes
Attribute | Description |
---|---|
name | The name of the attribute (used inside the component). |
type | Data type of the attribute (String, Integer, Boolean, etc.). |
description | Description of the attribute’s purpose. |
required | If set to true , the attribute must be passed. |
assignTo | Optionally binds to a variable in the component controller. |
Example 1: Creating a Custom Component With Attribute
MyComponent.component
xmlCopyEdit<apex:component>
<apex:attribute name="userName" type="String" description="User's Name" required="true" />
<h2>Welcome, {!userName}!</h2>
</apex:component>
Usage in a Visualforce Page:
xmlCopyEdit<apex:page>
<c:MyComponent userName="Mayank" />
</apex:page>
Example 2: Passing Dynamic Value
xmlCopyEdit<apex:page controller="MyController">
<c:MyComponent userName="{!currentUserName}" />
</apex:page>
When to Use <apex:attribute>
- While creating custom Visualforce components.
- To allow data binding and dynamic rendering in reusable UI blocks.
- Ideal for modular design and code reusability.
Best Practices
- Always provide a
description
for maintainability. - Use meaningful
name
attributes. - Mark attributes
required
when necessary to avoid runtime issues.