Search code examples
javascriptruby-on-railsjquery-select2-4

Initialize multiple selections in select2


I'm developing a multiple selection in Select2 4.0 and Rails 4.2.7.1. The code saves the right value in the database, but I've noticed a problem: it loses all value selection after a failed validation. How could i initialize all the value previously selected after a page reload? Thanks.

This is the current select2 declaration:

$(select_report).select2({
ajax: {
url: '/vaccination_plans/index_json',
dataType: 'json',
data: function (params) {
return {
  q: params.term
};
},
processResults: function (data, params) {
return {
  results: data
};
},
  cache: true
},
templateResult: function (data) {
  return data.vaccine_name;
},
templateSelection: function (data) {
  return data.vaccine_name;
},
minimumInputLength: 3
});

Solution

  • Actually all that was necessary was set the values (selection_array) server-side, then call the select2 initialization

    Es.

    <%= f.collection_select :attribute, selection_array, :id, :value, {}, {:class => 'form-control', :multiple => true} %>