Creating Hyperlinks in Visualforce

Visualforce provides a simple tag to create hyperlinks. This tag is called commandLink. The main advantage of using commandLink tag over the standard HTML <A href> is that commandLink allows us to use Apex methods and variables.

commandLink takes two attributes.

Action This attribute specifies the URL to which the link points to. If we need to call an Apex method we can include the method name in between{! and }. The example below calls the method newBookPage in the Apex class BookExtension.
Value This attribute specifies the text that needs to be displayed with the hyperlink.

As a simple example,
<apex:commandLink action=”” value=”Google”/>
is equivalent to
<a href=””>Google</a>

commandLink supports specifying query parameters to URLs. As an example, we can create the URL, using <apex:param>

<apex:commandLink action=”” value=”Google”>
<apex:param name="q" value="salesforce" assignTo="q"></apex:param>

However the real power of commandLink comes when we invoke Apex methods and access Apex variables to construct the URL and to display the text dynamically. The example below illustrates this.

<apex:page standardController="Book__c" extensions="BookExtension">
    <apex:commandLink action="{!newBookPage}" value="{!book.Name}">
        <apex:param value="{!}" assignTo="{!Id}"></apex:param>
        <apex:param value="{!book.Name}" assignTo="{!bookName}"></apex:param>

In the above example the Visualforce extension BookExtension has a method newBookPage. This method returns the URL of the next page that needs to be displayed. The action attribute of commandLink calls this method. The value attribute is also set dynamically based upon Apex variables.