Passing Parameters from a Command Button to Controller

Sometimes we need to pass parameters to the controller, on click of a Command Button. Here is a simple example how to pass parameters from a Command Button click to controller.

Note: Command Button pass parameters to controller, if we use a rerender attribute. So, here in below example I’ve used a rerender attribute with pageBlock component.

Visualforce Page:

<apex:page standardController="Contact" extensions="SampleControllerExtn">  
    <apex:form>
        <apex:commandButton value="Click Command Button" action="{!processCommandLink}" rerender="pb">
            <apex:param name="firstName" value="{!Contact.FirstName}" assignTo="{!firstName}"/>
            <apex:param name="lastName" value="{!Contact.LastName}" assignTo="{!lastName}"/>
        </apex:commandButton>
        <apex:pageBlock id="pb" rendered="false"></apex:pageBlock>
    </apex:form>
</apex:page>

Apex Class:

public class SampleControllerExtn {
    
    //Variables being set from the commandlink
    public String firstName {get; set;}
    public String lastName {get; set;}
    
    //Initialize the controller
    public SampleControllerExtn(ApexPages.StandardController stdCtrl) {
        
    }
    
    //Handle the action of the commandLink
    public PageReference processCommandLink() {
        System.debug('Contact Name - ' + firstName + ' ' + lastName);
        //Process the variable with your logic
        return null;
    }
}