Immediate attribute of commandbutton and commandlink in visualforce

Immediate attribute of commandbutton and commandlink in visualforce

This is basically used when we don’t want our validation rules to be fired during any server request.

It is a Boolean value that specifies whether the action associated with this component should happen immediately, without processing any validation rules associated with the fields on the page. If set to true, the action happens immediately and validation rules are skipped. If not specified, this value defaults to false.

We generally use it to make functionality of ‘Cancel’ button or ‘Back to Page’ button, where we don’t want validation rule to get executed. If we don’t use immediate=true then on click of cancel button also, validation rules will get executed.
VisualForce Component CommandButton

Click Here for Demo

Below is the visualforce page that has two fields and both are required.


<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 user clicks on any page request goes to controller but on click of save validation rules are fired, but on click of cancel button, they are not.

Below is the code for simple 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;
}
}

Permanent link to this article: http://www.sfdcpoint.com/salesforce/immediate-attribute-commandbutton-commandlink-visualforce/