Confirmation dialogs

Does anyone have any advice for how to guard destructive operations (e.g. delete resource) with a JS confirmation alert when rendering server-side (e.g. pug)?

We’re coming from rails, and that framework gives us (via ujs) some client-side JS to do that, which is triggered by data-* props.

Hi @gap777

You can just include it in there with conditional if
For edge:

<input name="username" type="text" />
@if(error.username)
  <span>error.username</span>
@endif
input(type='text' name='username')
if error.username
  span= error.username

You can also conditionally add whole modal in there or just data-* prop to already existing element

I don’t think I asked my question very clearly.
When a user clicks a link to delete something, I want to display a popup saying, “Are you sure?”. When they click no, the form is not submitted. Whey they click yes, the form is submitted to the server.
In rails, there are helpers to trigger browser-side functionality:

= f.submit "Delete", data: { confirm: "Are you sure you want to delete this project?" }

Is there anything in this environment to do that?

Gary

Hmm, seems like in Rails this is some helper that generates JS code? (or JS and HTML code)

There is no such helper in AdonisJS, but if you figure out HTML part and do it with Edge (add those data-* things) then you could still use same frontend JS library that handles JS part.

If Rails is generating required JS too, then you have to write JS on your own too, since Adonis does not have helpers for it.

But it’s actually good idea to make such helper library. I’ll write it down to my “make world a little better place” todo list :slightly_smiling_face:

Hi @gap777! :wave:

This is not in the scope of Adonis. Actually, Rails use the library jquery-ujs to achieve this (which isn’t Rails itself).

You can easily do it with plain JavaScript in your frontend code.

const confirmModals = document.querySelectorAll('[data-component="confirm-modal"]')

if (confirmModals.length > 0) {
    confirmModals.forEach((htmlElement) => {
        htmlElement.addEventListener('click', async function (e) {
            e.preventDefault()

            const prompt = confirm(this.getAttribute('data-message'))

            if (!prompt) {
                return
            }

            const href = this.getAttribute('href')

            const response = await fetch(href, {
                headers: new Headers({
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                }),
                method: this.getAttribute('data-method')
            })

            if (response.ok) {
                return window.location.reload()
            }

            alert("???")
        })
    })
}

And use it as follow:

<a href="/xxx"
    data-component="confirm-modal"
    data-method="delete"
    data-message="Are you sure?">
    Delete
</a>
1 Like