html code

The Immediate Attribute of CommandButton And CommandLink In Visualforce

This attribute is primarily used to bypass the firing of validation rules during server requests.

It’s a Boolean value that dictates whether the action linked with this component should occur instantly, disregarding any validation rules related to the page’s fields. When set to true, the action occurs immediately, skipping validation rules. If left unspecified, it defaults to false.

Commonly, it’s utilized in functionalities like ‘Cancel’ or ‘Back to Page’ buttons, where the execution of validation rules is undesirable. Without using immediate=true, even a click on the cancel button would trigger validation rules.

VisualForce Component CommandButton

Click Here for Demo

Here’s the Visualforce page containing two mandatory fields.

<apex:page standardController="Account" extensions="AccountExtension">
  <!-- Begin Default Content REMOVE THIS -->
  <apex:form >
      <apex:pageBlock >
      <apex:pageBlockButtons location="both">
                  <apex:commandButton value="Save" action="{!saveAccount}"/>
                  <apex:commandButton value="Cancel" immediate="true" action="{!cancelPage}"/>
      </apex:pageBlockButtons>
      <apex:pageBlockSection >
             <apex:inputField value="{!account.name}"/>
             <apex:inputfield value="{!account.Type}" required="true"/>
      </apex:pageBlockSection>
      <apex:outputText value="Account Added" rendered="{!isAdded}"/>
      <apex:outputText value="Account Not Added" rendered="{!isCancel}"/>
      </apex:pageBlock>
 </apex:form>
  <!-- End Default Content REMOVE THIS -->
</apex:page>

When a user initiates a page request, it gets directed to the controller. However, when the ‘Save’ button is clicked, validation rules are triggered. Conversely, upon clicking the ‘Cancel’ button, they remain inactive.

Here’s the code for a basic controller:

public with sharing class AccountExtension {
    public Boolean isAdded{get;set;}
    public Boolean isCancel{get;set;}
    public AccountExtension(ApexPages.StandardController controller) {
        isAdded = false;
        isCancel = false;
    }
public pagereference cancelPage(){
    isAdded = false;
    isCancel = true;
    return null;
}
 
public pagereference saveAccount(){
    isAdded = true;
    isCancel = false;
    return null;
}
}