Skip to content

Correctly instantiate select2 on newly created django inlines #249

Closed as not planned
@jurrian

Description

@jurrian

Describe the bug
When a new inline is added using the "Add another ..." button, the Select2 elements on that inline are not working.
Something similar has been proposed in an old PR, I've adapted it to the new situation.

If it's appreciated I can create a PR with the change I made.

Other possible related issues: applegrew#65, applegrew#32

Exception & Traceback
Clicking will provide no logs or trace.

Code Snippet
I've added this code to the django_select2/django_select2.js file in order to fix it:

$(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('.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
  })

To Reproduce

  1. Go to a Django page with inlines, the inlines should contain a select with a Select2Widget (not heavy).
  2. Click on "Add another" to add a new inline.
  3. Click on the select widget.
  4. Although there are options, clicking will do nothing.

Expected behavior
Normally the dropdown with options appears.

Screenshots
image
Clicking on the select will do nothing.

Metadata

Metadata

Labels

bugSomething isn't working

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions