diff -r 27ed26ca8623 -r 02a40997d8cb src/ztfy/myams/resources/js/ext/jquery-select2-sortable.js --- a/src/ztfy/myams/resources/js/ext/jquery-select2-sortable.js Fri May 12 14:03:02 2017 +0200 +++ b/src/ztfy/myams/resources/js/ext/jquery-select2-sortable.js Thu Oct 26 14:45:34 2017 +0200 @@ -4,6 +4,8 @@ * * author : Vafour * modified : Kevin Provance (kprovance) + * modified : Thierry Florac (tflorac@ulthar.net) + * Enable sorting for Select2 based on hidden inputs * inspired by : jQuery Chosen Sortable (https://github.com/mrhenry/jquery-chosen-sortable) * License : GPL */ @@ -24,38 +26,52 @@ var $select2 = $select.siblings('.select2-container'); var sorted; - // Opt group names - var optArr = []; - - $select.find('optgroup').each(function(idx, val) { - optArr.push (val); - }); - - $select.find('option').each(function(idx, val) { - var groupName = $(this).parent('optgroup').prop('label'); - var optVal = this; - - if (groupName === undefined) { - if (this.value !== '' && !this.selected) { - optArr.push (optVal); - } - } - }); - - sorted = $($select2.find('.select2-choices li[class!="select2-search-field"]').map(function () { - if (!this) { - return undefined; - } - - var id = $(this).data('select2Data').id; + if ($select.attr('type') === 'hidden') { + + // Update hidden field value + var plugin = $select2.data('select2'); + var separator = plugin.opts.separator; + var values = []; + $.each(plugin.data(), function() { + values.push(this.id); + }); + $select.val(values.join(separator)); + + } else { + + // Opt group names + var optArr = []; + + $select.find('optgroup').each(function(idx, val) { + optArr.push (val); + }); - return $select.find('option[value="' + id + '"]')[0]; - })); - - sorted.push.apply(sorted, optArr); - - $select.children().remove(); - $select.append(sorted); + $select.find('option').each(function(idx, val) { + var groupName = $(this).parent('optgroup').prop('label'); + var optVal = this; + + if (groupName === undefined) { + if (this.value !== '' && !this.selected) { + optArr.push (optVal); + } + } + }); + + sorted = $($select2.find('.select2-choices li[class!="select2-search-field"]').map(function () { + if (!this) { + return undefined; + } + + var id = $(this).data('select2Data').id; + + return $select.find('option[value="' + id + '"]')[0]; + })); + + sorted.push.apply(sorted, optArr); + + $select.children().remove(); + $select.append(sorted); + } }); return $this;