If you’re writing custom Lightning components you’ll eventually need to get a confirmation from the user before proceeding with some action. Perhaps you’ll need to ask approval before deleting a record, or maybe you’ll need final confirmation before launching the missiles. Either way - it’s going to happen and Salesforce isn’t helping you get the job done.
While Salesforce does provide a ton of super useful lighting components they don’t have any out of the box option that gives you power over the YES and the NO.
Don’t Fret!
Fear not - with a little JavaScript and some CSS styling (via the Lightning Design System) we can cook up a pretty spicy confirmation modal that’s rich with functionality and loaded to the top with configuration. Even better, our modal won’t leave your feeling bloated, stuffed, frustrated, or confused like those highly-processed modals you get on the sampler plate from your local fixer site.
Check this bad boy out…
As Easy as Pie
This thing isn’t a 12-speed Cuisinart, but some basic instructions are still needed. If you’re already a master chef at your keyboard, feel free to jump ahead and get the complete source for the component at the end.
The markup to add the confirmation modal to your component is simple…
Presenting the modal is just as easy. First get a handle on the component, then invoke the present
method…
Options
The modal’s title, message, and button labels can all be customized. All options are.. uhh.. optional.
They can either be configured in the markup…
… or in javascript when the modal is presented…
Handling the Modal Response
Lesser modals might require you to pass a function callback or some complicated state attributes to the component, making handling the user’s interaction complicated or kludgy.
The real power in this component is that we simply invoke the present()
method and wait for a response. If the user pressed the confirm
button, the modal’s promise resolves with a true
value. If the user canceled the modal it resolves with a false
value.
If you really want to impress your friends you can get fancy and use async/await…
Multiple Modals in the same component
Have a use case that requires multiple confirmation modals? I’ve got you covered, boss. Everything works the same except that you’ll first have to give each confirmation-modal component a unique data-id
…
You then simply use a different querySelector
to get a handle on the appropriate confirmation modal…
Show Me the Code!
Ok, enough of my jibber-jabber. You’re ready for those sweet bits and bytes. Enjoy and code responsibly!
Who We Are
At Restless Labs we have spent a significant part of the past decades offering digital consulting services to companies in a variety of industries - with a specialization in custom software solutions.
For more information about how we can help you, contact us today and discover what awesome things we can build together.