Skip to content

Commit

Permalink
fix(relations): refactor js and add it to forms Media class
Browse files Browse the repository at this point in the history
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
  • Loading branch information
b1rger committed Jan 23, 2025
1 parent ad54c56 commit 5e4a9c0
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
3 changes: 3 additions & 0 deletions apis_core/relations/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
14 changes: 10 additions & 4 deletions apis_core/relations/static/js/relation_dialog.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down

0 comments on commit 5e4a9c0

Please sign in to comment.