Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

I have an apex:commandButton on a visualforce page that invokes a method on the controller. There is currently no rerender value set for the button. Instead the controller method returns a PageReference to redirect the user as required.

E.g.

Visualforce:

<apex:commandButton value="Save" action="{!save}"/>

Controller:

public PageReference save() {
    // save body ...

    // return the user the a parent opportunity
    return new PageReference('/' + opp.Id);
}

Users are currently able to click on the resulting save button multiple times before the controller completes and returns the PageReference to redirect the browser to an opportunity.

How can I disable the commandButton after the first click?


I tried wrapping the commandButton in an actionStatus and facet, but the need to define the rerender property prevented the resulting PageReference redirect.

E.g.

This will render nicely in the browser and prevent multiple clicks, but doesn't redirect to the Opportunity on completion.

<apex:actionStatus id="saveStatus">
    <apex:facet name="stop">
        <apex:commandButton value="Save" action="{!save}" status="saveStatus" rerender="saveParentBlock" />
    </apex:facet>
    <apex:facet name="start">
        <apex:commandButton value="Saving..." disabled="true" status="saveStatus"/>
    </apex:facet>
</apex:actionStatus>

There is a similar question Using jQuery to disable VF page button onclick. I need to support an existing PageReference redirect, which slightly alters the requirements.

Force.com Discussion Boards: Disabling a commandButton to prevent double submission

Ideas: Disable command buttons on click in visualforce as standard

share|improve this question

4 Answers 4

up vote 5 down vote accepted

The mechanism I have found to be most maintainable uses a JavaScript function called by an element's click event, which internally calls an actionFunction to post the form, disables the buttons on the page and then returns false on the commandlink/button. This is used in conjunction with an oncomplete on the actionFunction to re-enable the buttons when the form has been (ajax) posted and returns a result to the page.

Without the rerender attribute the form performs a full postback along with the disabling of the buttons.

Note: You can't disable the button(s) before the form is posted or the data sent to the controller will not include which button/link within the form was clicked and thus which action to execute.

<script src="//ajax.googleapis.com/ajax/libs/jquery/latest/jquery.js"></script>
<script>

    function buttonsEnabled(enabled) {
        // retrieve all of the buttons or links on the page
        // with the css class of btn
        var $buttons = jQuery('.btn');
        if (enabled === false) {
            // add the btnDisabled class to give it the look of being disabled
            // add the disabled attribute to actually disable interactability
            $buttons.toggleClass('btnDisabled', true).attr('disabled', 'disabled');
        } else {
            // remove the css class and the disabled attribute
            $buttons.toggleClass('btnDisabled', false).attr('disabled', null);
        } 
    }

    function doSomeWork() {
        // first, call the action function to post the form
        doSomeWorkActionFunction();

        // second, disable the buttons
        buttonsEnabled(false);

        // third, return false to prevent the click from
        // posting the form a second time
        return false;
    }

</script>

<apex:form>

    <apex:actionFunction name="doSomeWorkActionFunction" 
        action="{!yourControllerMethod}" 
        oncomplete="buttonsEnabled(true);"
        rerender="whateverYouNeedToRerender"></apex:actionFunction>

    <apex:commandLink action="{!yourControllerMethod}" 
        value="Your Text Here" 
        id="theCommandLink" 
        onclick="return doSomeWork();" />

</apex:form>
share|improve this answer
    
Will this work where the controller method that the action calls returns a PageReference that the user should be redirected to? I don't need to do an ajax rerender of a component. –  Daniel Ballinger Mar 26 '13 at 21:00
    
Yes, just don't specify the rerender attribute info on the apex tags, return a PageReference on the action method and it'll behave exactly that way. This also doesn't use a setTimeout method call because you don't need it. You simply need to control the order in which these actions in the page occur. Using a setTimeout implementation allows the user the ability (albeit small) the ability to submit twice while the script pauses the action of disabling of the buttons. –  Mark Pond Mar 26 '13 at 23:29
    
Mark - I don't understand why both the commandLink and the actionFunction are calling the same yourControllerMethod. Does the commandLink's action get bypassed by the onclick? –  David Cheng Mar 18 at 23:54
    
@DavidCheng, yes you are correct. The <apex:commandlink /> doesn't need the action attribute on it as it won't ever be executed. Since the JavaScript is executed first and then that function returns false the click action on the link itself does not take place. So, the form post is happening via the actionFunction rather than the link click. –  Mark Pond Mar 20 at 18:29

This is one possible solution, I'm still keen to see if there is a better way of doing this, such as getting the actionStatus and facet to work with a PageReference redirect.


If the commandButton onclick event is used to immediately disable the button the post back to the controller method won't occur.

This won't work:

<apex:commandButton id="save" value="Save" action="{!save}" 
     onclick="this.disabled='disabled';return true;" />

Instead, create a JavaScript function that will disable the button after a short timeout via the commandButtons onclick event. You could inline this all into the onclick as required. I found it easier to split the functions out so I could disable other related buttons, etc.

<script>
    function disableOnSubmit(input) {
        setTimeout('disableAfterTimeout(\'' + input.id + '\');', 50);
    }
    function disableAfterTimeout(id) {
        var toDisable = document.getElementById( id );
        toDisable.disabled = 'disabled';
        // Use the Salesforce CSS style to make the button appear disabled
        toDisable.className = 'btnDisabled';
        toDisable.value = "Saving..."
    }
</script>

<apex:commandButton id="save" value="Save" action="{!save}" onclick="disableOnSubmit(this);" />
share|improve this answer
    
I've tried this for Save/Cancel buttons, and for "punch-out" buttons--where the user navigates temporarily to another form--using both direct GETs from the page and controller-action redirects. Works flawlessly. I extended it a little to allow the value (the button label after onClick) to be passed in from the button declaration. –  Eric Fournier Jun 12 at 12:59

Try commandButton with actionFunction:

<commandButton onclick="disableMe" oncomplete="runActionJS();"/>
<actionFunction name="runActionJS" action"{!action}"/>
share|improve this answer
    
Will the actionFunction respect the PageReference returned by the controller action and redirect the user? Also, how does the disableMe function work? If it disables the button too soon nothing will happen. –  Daniel Ballinger Mar 26 '13 at 21:02
    
Yes it respects the pageReference. This actually took me a while to figure out! disableMe is a JS function that just sets the style of the button to disabled (grays it out). –  user1936026 Apr 3 '13 at 16:41

This seems to work:

<apex:commandButton value="Save" onclick="this.onclick=function(){return false;}" action="{!SaveAll}"  />

It appears that the first time through, the event listeners fire before the onclick gets replaced by the "do nothing" function. So I can press the button as often as I want but only the first press counts. None of the actionfunction / rerender things worked for my whole page submit, but this does, and it's simple.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.