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=”http://www.google.com” value=”Google”/>
is equivalent to
<a href=”http://www.google.com”>Google</a>

commandLink supports specifying query parameters to URLs. As an example, we can create the URL http://www.google.co.in/search?q=salesforce, using <apex:param>

<apex:commandLink action=”http://www.google.com/search” value=”Google”>
<apex:param name="q" value="salesforce" assignTo="q"></apex:param>
</apex:commandLink>

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="{!book.id}" assignTo="{!Id}"></apex:param>
        <apex:param value="{!book.Name}" assignTo="{!bookName}"></apex:param>
    </apex:commandLink>
</apex:page>

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.