From 5e4a9c04b3bd882a8afd84729b48bcc7f7e9924b Mon Sep 17 00:00:00 2001 From: Birger Schacht Date: Wed, 22 Jan 2025 19:11:44 +0100 Subject: [PATCH] fix(relations): refactor js and add it to forms Media class The reinit_select2 functionality is now in a separate `rel_reinit_select2` function which is run every time the js is included *and* when the `reinit_select2` trigger is received (though not sure if thats even needed now). In addition the javascript is included in the relation forms Media class, so that the js is included with every relation form and thus the `rel_reinit_select2` function is executed everytime the form in loaded which is what we actually want to make the select2 work everytime. Closes: #1544 --- apis_core/relations/forms.py | 3 +++ apis_core/relations/static/js/relation_dialog.js | 14 ++++++++++---- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/apis_core/relations/forms.py b/apis_core/relations/forms.py index 11d4b5e4e..40abc685a 100644 --- a/apis_core/relations/forms.py +++ b/apis_core/relations/forms.py @@ -40,6 +40,9 @@ class RelationForm(GenericModelForm): can then select the success_url based on the `reverse` state). """ + class Media: + js = ["js/relation_dialog.js"] + class Meta: fields = "__all__" widgets = { diff --git a/apis_core/relations/static/js/relation_dialog.js b/apis_core/relations/static/js/relation_dialog.js index 4b913d57e..7dfb1579c 100644 --- a/apis_core/relations/static/js/relation_dialog.js +++ b/apis_core/relations/static/js/relation_dialog.js @@ -3,19 +3,25 @@ function tohtml(item) { span.innerHTML = item.text; return span; } -document.body.addEventListener("reinit_select2", function(evt) { - form = document.getElementById(evt.detail.value); - form.querySelectorAll(".listselect2, .modelselect2multiple, .modelselect2").forEach(element => { + +function rel_reinit_select2() { + document.querySelectorAll(".listselect2, .modelselect2multiple, .modelselect2").forEach(element => { $(element).select2({ ajax: { url: $(element).data("autocomplete-light-url"), }, - dropdownParent: $(form), + dropdownParent: $(element.form), templateResult: tohtml, templateSelection: tohtml, }); }); $('.select2-selection').addClass("form-control"); +} + +rel_reinit_select2(); + +document.body.addEventListener("reinit_select2", function(evt) { + rel_reinit_select2(); }); document.body.addEventListener("dismissModal", function(evt) { document.getElementById("relationdialog").close();