Customizing Confirmation Dialogs in Rails
written by Dejan on July 18, 2012
Rails UJS will use the window.confirm() if you want to confirm a link click. It allows you to customize this to use a library like Bootstrap, Noty or your own. The problem is customizing doesn't work. It doesn't work because it expects your custom to return 'true' or 'false,' just like window.confirm() does. Your custom method, however, does not block the browser, like window.confirm() does, nor can it, so the call to your custom method returns without waiting for user input.
The simplest way I found to customize the Rails UJS confirmation process and make it work asynchronously, is to override $.rails.allowAction. The idea is to display confirmation dialog and add callback to the OK button click event. That callback will remove the data-confirm attribute from the link which will essentially make it non-confirmable (if you could click on it again, it would be executed without any confirmation). So all you need really is to trigger the 'click' event again on that link (the actual name of the event is 'click.rails') and close the confirmation dialog.
Here's the overridden implementation of the allowAction and callback we'll add for the click on the OK button on the confirmation dialog. You also need to pick one of the implementations of the showConfirmDialog below, depending on the library you're using.
Do this to override Rails, then also pick your library and do that, too.
Bootstrap
http://twitter.github.com/bootstrap/javascript.html#modals
jQueryUI
http://jqueryui.com/demos/dialog/#modal-confirmation
Noty
http://needim.github.com/noty/
Leave a Comment


5 Comments
Have you seen the async branch of jquery-ujs? That does what you do, only better :)
https://github.com/akzhan/jquery-ujs/tree/asynchronous-call-to-confirm
Referenced from this pull request: https://github.com/rails/jquery-ujs/pull/196
Here’s my solution with async branch mentioned by Jeroen http://codetunes.com/2012/04/15/how-i-learnt-about-jquery-deffered-thanks-to-rails
Thanks for the links. Using a fork of jquery-ujs wasn’t appealing to me.
Hello
Thanks for your code.. It works fine with GET HTTP link, but for AJAX link with data-remote = “true”, it’s not working ;-((((((((((
The dialog box is fine, but when you click on ‘OK’, the link.trigger(‘click.rails’) call raises an error :
evt.ctrlKey is undefined
dude forget the haters above (jeroen). thanks for this example, it helped me move past a road block