Skip to content

Commit

Permalink
Implement warning when leaving an unsubmitted form
Browse files Browse the repository at this point in the history
Signed-off-by: Christian Hartmann <chris-hartmann@gmx.de>
  • Loading branch information
Chartman123 committed Sep 6, 2022
1 parent 25d834f commit e67b140
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions src/views/Submit.vue
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,25 @@ export default {
mixins: [ViewsMixin],
/*
* This is used to confirm that the user wants to leave the page
* if the form is unsubmitted.
*/
beforeRouteLeave(to, from, next) {
// beforeRouteLeave is called when the static route changes.
// Cancel the navigation, if the form has unsaved edits and the user did not
// confirm leave. This prevents accidentally losing changes
if (this.confirmStayInEditedForm()) {
next(false)
} else {
// We have to check if the target component stays the same and reload.
// However, we should not reload if the component changes; otherwise
// reloaded data may overwrite the data loaded at the target component
// which will at the very least result in incorrect breadcrumb path!
next()
}
},
props: {
isLoggedIn: {
type: Boolean,
Expand All @@ -150,6 +169,7 @@ export default {
answers: {},
loading: false,
success: false,
submitForm: false,
}
},
Expand Down Expand Up @@ -222,6 +242,13 @@ export default {
},
},
beforeDestroy() {
window.removeEventListener('beforeunload', this.beforeWindowUnload)
},
created() {
window.addEventListener('beforeunload', this.beforeWindowUnload)
},
beforeMount() {
// Public Views get their form by initial-state from parent. No fetch necessary.
if (this.publicView) {
Expand Down Expand Up @@ -256,11 +283,32 @@ export default {
this.$refs.submitButton.click()
},
/*
* Methods for catching unwanted unload events
*/
beforeWindowUnload(e) {
if (this.confirmStayInEditedForm()) {
// Cancel the window unload event
e.preventDefault()
e.returnValue = ''
}
},
confirmLeavingPage() {
return confirm(t('forms', 'You have unsaved changes! Do you still want to leave?'))
},
confirmStayInEditedForm() {
return (
!this.submitForm
&& !this.confirmLeavingPage()
)
},
/**
* Submit the form after the browser validated it 🚀
*/
async onSubmit() {
this.loading = true
this.submitForm = true
try {
await axios.post(generateOcsUrl('apps/forms/api/v2/submission/insert'), {
Expand All @@ -284,6 +332,7 @@ export default {
this.answers = {}
this.loading = false
this.success = false
this.submitForm = false
},
},
Expand Down

0 comments on commit e67b140

Please sign in to comment.