2

I'm creating a formset in which one of the field in select2 field and when i clicked on add more, i'm cloning that row. All the other columns are cloning but the select 2 is not displaying.

function newSelect2WidgetInFormset (cell, prefix) {
    var $cell = $(cell),
        $script = $cell.find("script"),
        $input = $cell.find("input[type=hidden][id^=id_]"),
        scriptText, newId, newScriptText;

    // Remove old container
    $cell.find(".select2-container").remove();
    **scriptText = $script.text();** --------------------- This script was coming blank and it could not generate the select2 field
    newId = $input.attr("id");
    console.log("Before", scriptText);

    newScriptText = scriptText.replace(/id_[\d\w\-]+/g, newId);
    $script.text(newScriptText);
    console.log("After", newScriptText);
    if (scriptText === newScriptText) {
        console.warn("New script and old have some code");
        console.warn("Should had been changed to ", newId);
    }

    // Script evaluation forced evaluation is needed because
    // inserting elements with script tag does not make the browser
    // to execute them
    eval(newScriptText);
    // swal("Script", newScriptText, "info");

}

Note:- We have recently updated the django_select2 from 4.2.2 to latest version. When i checked inside the code the Select2Mixin has the render method which appends render_js_code function

s += self.render_js_code(id_, name, value, attrs, choices)

But in the latest version, i couldn't find the render method and even the render_js_code. What is the replace of that and how can we create a clone of the select2 field.

We are struggling with this from the past 3 weeks, any help from the team/community would be greatful.

1 Answers1

0

Have you considered using django-dynamic-formset ? It looks to me that you are doing this by hand, and it might be not needed at all. I am using exactly the same you are talking about but with django-dynamic-formset. Please be aware that you need to use updated version that was not yet commited or you wont get remove buttons:

https://github.com/Dowsley/django-dynamic-formset/commit/1a781fd6b1a7a5f6348b43097983773f0d2a69de

Branko Radojevic
  • 660
  • 1
  • 5
  • 14