[SalesForce] Cancel Button Event Throwing a Required field Validation Error

When i am clicking on cancel button, validation error for required name field is thrown.
As per my understanding when we click an action method :
1. entire form is submitted
2. Its checked for validation error
3. Perfom the action methods.

If I am right then that could be the reason for the validation error. Please correct me if i am wrong.

My question : cause for validation error thrown and what could be the work around if i want my cancel button to work without filling the name field ?

Apex Controller :

 public class myCustomController{
  public Account myAccount {get;set;}
  public myCustomController(){}
  public PageReference save(){}
  public PageReference cancel(){
    //Send them back to the Accounts tab
    return new PageReference('/001/o');
  }

  }

Apex Page :

<apex:page controller="myCustomController">
  <apex:pageMessages id="pageMessages" />  
  <apex:form>
    <apex:pageBlock title="Account Edit" mode="edit" >
      <apex:pageBlockButtons>
        <apex:commandButton value="Save" action="{!save}" />
        <apex:commandButton value="Cancel" action="{!cancel}" />
      </apex:pageBlockButtons>
      <apex:pageBlockSection title="Account Info" columns="3" >
        <apex:inputField value="{!myAccount.name}" />
        <apex:inputField value="{!myAccount.phone}" />
      </apex:pageBlockSection>
    </apex:pageBlock>
  </apex:form>
</apex:page>

Best Answer

You have to change your cancel button code as :

<apex:commandButton value="Cancel" action="{!cancel}" immediate="true" />

specifying immediate attribute to true will tell that page validations can be skipped while performing actions of the button.

To know more you can refer this link.

Related Topic