Understanding apex:commandLink Component in Visualforce

The <apex:commandLink> component creates a clickable link that behaves like a button—triggering an action defined in the controller when clicked.


Syntax

xmlCopyEdit<apex:commandLink value="Click Here" action="{!doSomething}" />

Key Attributes

AttributeDescription
valueThe text displayed as the link.
actionThe controller method called when the link is clicked.
immediateOptional. Skips validation if set to true.
reRenderOptional. Rerenders parts of the page using AJAX.
styleClassOptional. Applies CSS class for styling.
targetOptional. Opens the link in a specified target window/tab.

Example 1: Basic Usage

xmlCopyEdit<apex:form>
    <apex:commandLink value="View Details" action="{!viewDetails}" />
</apex:form>
  • Calls the viewDetails method when the user clicks the link.

Example 2: Link With ReRender

xmlCopyEdit<apex:form>
    <apex:commandLink value="Get Message" action="{!getMessage}" reRender="outputMsg" />
    <apex:outputPanel id="outputMsg">
        <apex:outputText value="{!message}" />
    </apex:outputPanel>
</apex:form>
  • Refreshes the message display area without reloading the full page.

Example 3: Link Inside a Table

xmlCopyEdit<apex:dataTable value="{!accounts}" var="acc">
    <apex:column headerValue="Name">
        <apex:commandLink value="{!acc.Name}" action="{!viewAccount}">
            <apex:param name="accountId" value="{!acc.Id}" assignTo="{!selectedAccountId}" />
        </apex:commandLink>
    </apex:column>
</apex:dataTable>
  • Each link passes the account ID to the controller when clicked.

When to Use <apex:commandLink>

  • When you want to use a hyperlink to invoke controller logic.
  • Great for actions like view, edit, or delete in table rows.
  • Ideal when you want a button-like behavior but with a hyperlink appearance.

Best Practices

  • Always wrap <apex:commandLink> inside a <apex:form>.
  • Use reRender for AJAX-based UI updates.
  • Combine with <apex:param> to pass values dynamically.