Skip to content

Commit

Permalink
fix(django-select2): Add re-initialization for django-select2 on form…
Browse files Browse the repository at this point in the history
… change to handle new inlines (#1409)
  • Loading branch information
drikusroor authored Dec 2, 2024
1 parent 87e2ac1 commit ea4f366
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions backend/experiment/static/experiment_form.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
document.addEventListener("DOMContentLoaded", function () {
initCollapsibleInlineForms();
floatingSubmitRow();

// TODO: Remove this in the future once the issue is fixed in django-select2
// re-initialize django-select2 on form change
reinitializeDjangoSelect2OnFormChange();
});

function initCollapsibleInlineForms() {
Expand Down Expand Up @@ -60,3 +64,43 @@ function floatingSubmitRow() {
}
});
}
/**
* Re-initialize django-select2 on form change.
* This is needed because django-select2 is not re-initialized on new inlines.
* Let's check again in the future if this issue is fixed in django-select2
* and remove this function.
* See also: https://github.com/codingjoe/django-select2/pull/300
* @returns {void}
*/
function reinitializeDjangoSelect2OnFormChange() {

const $ = django.jQuery;

return $(function () {
$('.django-select2').djangoSelect2()

// This part fixes new inlines not having the correct select2 widgets
function handleFormsetAdded(row, formsetName) {
// Converting to the "normal jQuery"
var jqRow = django.jQuery(row)

// Because select2 was already instantiated on the empty form, we need to remove it, destroy the instance,
// and re-instantiate it.
jqRow.find('.django-select2').parent().find('.select2-container').remove()
jqRow.find('.django-select2').djangoSelect2('destroy');
jqRow.find('.django-select2').djangoSelect2()
}

// See: https://docs.djangoproject.com/en/dev/ref/contrib/admin/javascript/#supporting-versions-of-django-older-than-4-1
django.jQuery(document).on('formset:added', function (event, $row, formsetName) {
if (event.detail && event.detail.formsetName) {
// Django >= 4.1
handleFormsetAdded(event.target, event.detail.formsetName)
} else {
// Django < 4.1, use $row and formsetName
handleFormsetAdded($row.get(0), formsetName)
}
})
// End of fix
})
}

0 comments on commit ea4f366

Please sign in to comment.