Customizing Confirmation Dialogs in Rails

Guest article by written by on Jul 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/

A nice follow up article by PJ McCormick.

Get Blog Updates