Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4.1.4 Custom Confirmation Alert

I'm using Rails 4.1.4 in my app. I have a link to a delete method which has the data-confirm attribute so a confirmation dialog appears before continuing with the action.

<%= link_to t(:delete_account), delete_account_path, method: :delete, class: "btn btn-danger btn-sm", data: { confirm: t(:delete_account_confirmation_text) } %>

The confirmation dialog that appears is the browser's default. How can I customize this to use Bootstrap modal for example?.

Regards!!!.

like image 380
Luis Crespo Avatar asked Oct 09 '14 23:10

Luis Crespo


2 Answers

Using some custom coffeescript, like:

$ ->
  $.rails.allowAction = (link) ->
    return true unless link.attr('data-confirm')
    $.rails.showConfirmDialog(link) 
    false 

  $.rails.confirmed = (link) ->
    link.removeAttr('data-confirm')
    link.trigger('click.rails')

  $.rails.showConfirmDialog = (link) ->
    message = link.attr 'data-confirm'
    html = """
           <div class="modal" id="confirmationDialog">
             <div class="modal-dialog">
               <div class="modal-content">
                 <div class="modal-header">
                   <a class="close" data-dismiss="modal">×</a>
                   <h1>#{message}</h1>
                 </div>
                 <div class="modal-footer">
                   <a data-dismiss="modal" class="btn">#{link.data('cancel')}</a>
                   <a data-dismiss="modal" class="btn btn-primary confirm">#{link.data('ok')}</a>
                 </div>
               </div>
             </div>
           </div>
           """
    $(html).modal()
    $('#confirmationDialog .confirm').on 'click', -> $.rails.confirmed(link)

This also immediately allows to translate your ok and cancel buttons, like

data: { confirm: t('messages.confirm_delete'), ok: t('buttons.ok'), cancel: t('buttons.cancel')

If you don't always want to repeat this, use some helper to create a custom "delete link"!

like image 136
Danny Avatar answered Oct 04 '22 20:10

Danny


You can try to use a gem (data-confirm-modal) for this.

like image 44
Leandro Moreira Avatar answered Oct 04 '22 22:10

Leandro Moreira