How to add a confirm dialog to a command button?

  • I'd think this would work just fine, but it seems to prevent the action function from firing regardless of the confirm response

    <apex:commandButton value="Remove All" action="{!removeAll}" rerender="form"
         status="LoadingStatus" onclick="return confirm('Are you sure?');"/>
    

    `onclick="return confirm('Are you sure?');"` works fine in Firefox and Chrome right now. If user says OK (Yes) an action is executed. Maybe Salesforce fixed this issue.

  • Bob Roberts

    Bob Roberts Correct answer

    8 years ago

    I know this has been answered but I thought I would toss my hat into the ring. Taking a look at the code generated by the commandButton tag, the onclick code goes before salesforce's own code to call the controller method. What this means is

    onclick="return confirm('Are you sure?');"
    

    is always returning before calling the code to the controller method. What I have done is to wrap the return in an if statement and call it only if the condition is correct. The code below will call return if the confirmation is false.

    onclick="if(!confirm('Are you sure?')){return false};"
    

    So the important thing is that if you want the salesforce action method to get called make sure any onclick javascript does NOT return, right?

    @Ralph exactly! The action method gets translated into a log bit of JS code and tack onto the end of the onClick.

    very interesting... and counter-intuitive. Adding this to the list of salesforce gotcha's

    Doesn't work for me unless you actually return false...

    PLEASE NOTE:--- WRT the onclick JS --- void method: Action will execute --- return null: Action will execute --- return true: Action will execute --- return false: Action will NOT execute --- onclick="if(!confirm('Are you sure?')){return false};" --- is over engineered. --- return confirm('Are you sure?'); --- is more correct.

    If someone wants to evaluate the object before the Confirmation pops --- do something like this --- return "{!contract.Status}" != "Draft" || confirm("Please check your details in the Contract are Correct, before you proceed"); --- in this example the first logical is evaluated first and if found to be true the second logical it is OR'd with is then not evaluated. If the first is found to be false the confirmation is fired.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used