在我的情况下,隐藏字段解决方案是一个很好的解决方案,但 Select2 插件仍然保持数字/字母(?)顺序,这不是用户选择的顺序
我找到了一个解决方案,可以解决我的所有需求。
在我的 symfony 表单声明中将有一个名为 selectOrder 的隐藏字段,用于保存当前订单:
$("#form_people").on('change', function(){
var data = $(this).select2('data');
var array = [];
$.each(data, function(index, val) {
array[index]=val.id;
});
array.join(',');
$("#selectOrder").val( array );
});
在表单声明后的 javascript 部分有我的 Multi Select2:
var sel = $("#form_people").select2({
maximumSelectionSize: 3,
minimumInputLength: 1,
escapeMarkup: function(m) { return m; },
});
然后
//After reloading page you must reselect the element with the
//right previous saved order
var order = $("#selectOrder").val().split(",");
var choices = [];
for (i = 0; i < order.length; i++) {
var option = $('#form_people option[value="' +order[i]+ '"]');
choices[i] = {id:order[i], text:option[0].label, element: option};
}
sel.select2('data', choices);
这是我需要的,也许可以帮助其他开发者