Disabling a command button on click in VisualForce
KeyWords: #VisualForce, #ActionSupport, #CommandButton, #Salesforce
How do you avoid users from clicking on a button several times? Disabling the button on click is the obvious solution but how do we achieve this without having to resort to Javascript? Here’s how I did it using actionSupport.
By using ActionSupport, disable a command button when it is clicked.
ActionSupport allows the outputPanel containing the button to be refreshed before the Save action is submitted. The click event calls the captureButtonClick action, which registers the button click in the form of the private variable, hasBeenClickedAlready, by setting it to true. The getter, disableSaveButton, in turn returns true, disabling the command button.
<apex:page><apex:pageBlockButtons location="bottom">
<apex:outputPanel id="buttons">
<apex:commandButton value="Confirm" action="{!Save}" disabled="{!disableSaveButton}">
<apex:actionSupport event="onclick" action="{!captureButtonClick}" reRender="buttons"/>
</apex:commandButton>
<apex:commandButton value="Cancel" action="{!cancel}" />
</apex:outputPanel>
</apex:pageBlockButtons></apex:page>--------------------------------------------------------------------public with sharing class VFPageController {
@TestVisible
private boolean hasBeenClickedAlready = false; public PageReference captureButtonClick() {
hasBeenClickedAlready = true;
return null;
} public Boolean disableSaveButton {
get {
return hasBeenClickedAlready;
}
}
}