Skip to content

Commit

Permalink
feat: warn unsaved form (#655)
Browse files Browse the repository at this point in the history
  • Loading branch information
lukasvinclav committed Aug 6, 2024
1 parent 6023e24 commit c36f846
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 1 deletion.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,9 @@ class CustomAdminClass(ModelAdmin):
# Display fields in changeform in compressed mode
compressed_fields = True # Default: False

# Warn before leaving unsaved changes in changeform
warn_unsaved_form = True # Default: False

# Preprocess content of readonly fields before render
readonly_preprocess_fields = {
"model_field_name": "html.unescape",
Expand Down
1 change: 1 addition & 0 deletions src/unfold/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,7 @@ class ModelAdmin(ModelAdminMixin, BaseModelAdmin):
list_disable_select_all = False
compressed_fields = False
readonly_preprocess_fields = {}
warn_unsaved_form = False
checks_class = UnfoldModelAdminChecks

@property
Expand Down
23 changes: 23 additions & 0 deletions src/unfold/static/unfold/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,31 @@ window.addEventListener("load", (e) => {
renderCharts();

filterForm();

warnWithoutSaving();
});

/*************************************************************
* Warn without saving
*************************************************************/
const warnWithoutSaving = () => {
let formChanged = false;

Array.from(
document.querySelectorAll(
"form.warn-unsaved-form input, form.warn-unsaved-form select"
)
).forEach((field) => {
field.addEventListener("change", (e) => (formChanged = true));
});

window.addEventListener("beforeunload", (e) => {
if (formChanged) {
e.preventDefault();
}
});
};

/*************************************************************
* Filter form
*************************************************************/
Expand Down
2 changes: 1 addition & 1 deletion src/unfold/templates/admin/change_form.html
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@

{% block content %}
<div id="content-main">
<form {% if has_file_field %}enctype="multipart/form-data" {% endif %}{% if form_url %}action="{{ form_url }}" {% endif %}method="post" id="{{ opts.model_name }}_form" novalidate>
<form {% if has_file_field %}enctype="multipart/form-data" {% endif %}{% if form_url %}action="{{ form_url }}" {% endif %}method="post" id="{{ opts.model_name }}_form" {% if adminform.model_admin.warn_unsaved_form %}class="warn-unsaved-form"{% endif %} novalidate>
{% csrf_token %}

{% block form_top %}{% endblock %}
Expand Down

0 comments on commit c36f846

Please sign in to comment.