Understanding apex:attribute Component in Visualforce

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

AttributeDescription
nameThe name of the attribute (used inside the component).
typeData type of the attribute (String, Integer, Boolean, etc.).
descriptionDescription of the attribute’s purpose.
requiredIf set to true, the attribute must be passed.
assignToOptionally 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.