How to initialize the selection for rails-select2

2019-03-05 06:45发布

问题:

The project uses marionette-rails, backbone-on-rails, select2-rails and this port to BackboneForms to provide a multiselect form field. The select options are available to the user. They are retrieved from the collection containing the total list of options:

MyApp.module("Products", function(Products, App, Backbone, Marionette, $, _) {

  Products.CustomFormView = Products.CustomView.extend({

    initialize: function(options) {
      this.model.set("type", "Product");
      Products.EntryView.prototype.initialize.apply(this, arguments);
    },

    schemata: function() {
      var products = this.collection.byType("Product");
      var productTypes = products.map(function(product){
        return {
          val: product.id,
          label: product.get("name")
        };
      });

      return {
        productBasics: {
          name: {
            type: "Text",
            title: "Name",
            editorAttrs: {
              maxLength: 60,
            }
          },
          type: {
            type: 'Select2',
            title: "Product type",
            options: {
              values: productTypes,
              value: [3, 5],
              initSelection: function (element, callback) {
                var data = [];
                $(element.val().split(",")).each(function () {
                  data.push({id: this, text: this});
                });
                callback(data);
              }
            },
            editorAttrs: {
              'multiple': 'multiple'
            }
          }
        }
      };
    }

  });
});

Do I initialize the value correctly in options.value? How comes initSelection is never called? I copied the function from the documentation - it might be incomplete for my case. None of the products with the IDs 3 and 5 is displayed as the selection.

回答1:

initSelection is only used when data is loaded asynchronously. My understanding is that there is no way of specifying the selection upon initialization if you are using an array as the data source for a Select2 control.

The best way of initializing the selection is by using setValue after the form is created. Here is a simplified example based on the code in your example.

var ProductForm = Backbone.Form.extend({
  schema: {
    type: {
      type: 'Select2',
      title: "Product type",
      options: {
        values: productTypes,
      },
      editorAttrs: {
        'multiple': 'multiple'
      }
    }
  });

var form = new ProductForm({
  model: new Product()
}).render();

form.setValue("type", [3, 5]);


回答2:

You can use value function (http://ivaynberg.github.io/select2/#documentation) in setValue. I personally recomend you to use this backbonme-forms plugin: https://gist.github.com/powmedia/5161061 There is a thread about custom editors: https://github.com/powmedia/backbone-forms/issues/144