Tobias
Tobias

Reputation: 964

How to dynamically initialise FilteredSelectMultiple in django

I am trying to use the FilteredSelectMultiple widget on a custom non-admin site with a dynamic formset. I have gotten the widget to display properly for the existing entries in the formset by including:

<script type="text/javascript" src="/static/admin/js/jquery.min.js"></script>
<script type="text/javascript" src="/static/admin/js/jquery.init.js"></script>
<script type="text/javascript" src="/admin/jsi18n"></script>

However, when I add another entry in my formset (I tried both using this plugin and by calling a form factory view with ajax) the widget displays as if it was a normal select widget, as if the initialisation scripts are not run.

How can I properly initialise further instances of the FilteredSelectMultiple widget on the fly?

Upvotes: 0

Views: 784

Answers (1)

Skander
Skander

Reputation: 230

The way the widget is written initializes it only on page load, so additional widgets that you add do NOT get initialized. The way to handle this is to link into the "added" event generated by the django dynamic formets. The following code I think will only work if you have a single one of these widgets - you might have to write a loop to iterate over the widgets if you have more than one per 'row'. Sorry it isn't the cleanest code in the world, but it works for my purposes:

function enableHorizFilter(row){
    /* Row contains the whole row, select only our input box.
     * This could break if there are multiple widgets like this, I think. */
    filterbox = $(".selectfilter", row);
    //Selectfilter needs the ID
    filterboxID = filterbox.attr("id");
    /* Copied params from the source of the page, might break things if
     * I change the defaults, hardcoded */
    SelectFilter.init(filterboxID, "DATACLASSHERE", 0, "/static/admin/");
}

//this adds the formset controls
$('#YOURFORMIDHERE').formset({
  //every time something is added, do the following
  added: function(row){
    enableHorizFilter(row);
  }
});

Upvotes: 2

Related Questions