How to initialize the selection for rails-select2 in BackboneForms schema?
Asked Answered
F

2

0

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.

Fiord answered 13/7, 2013 at 21:11 Comment(0)
L
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]);
Lira answered 26/7, 2013 at 7:25 Comment(0)
M
1

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

Mclean answered 14/7, 2013 at 9:8 Comment(7)
Thanks for the documentation hint. I understand that I have to set the selection as options: { value: [3, 5] }. Where should I provide initSelection? Do I need to extend the editor for backbone-forms? Please add some code snippets.Fiord
I can see how you load the config from the schema in gist:5161061. But can you specify how you define options.value resp. config.value and initSelection if needed? Please add some code.Fiord
I guess initSelection belongs into the options as the documentation states: "Notice that in order to use this method you must define the initSelection function in the options ..."Fiord
Hi! I think you don't need initSelection until you begin to use some remote features e.g. ajax loading. You just need to provide options in config object just like with HTML page. "nodeType": { "title": "Node type", "type": "Select2", "config": { "tags": ["tag 1","tag 2","tag 3","tag 4","tag 5","tag 6","tag 7"], "width": "300" } } or state: { title: 'State', type: 'Select2', config: {width: '300', data: [{id:'1',text:'State 1'},{id:'2',text:'State 2'}]}} And yeah: use gist.github.com/powmedia/5161061 until you need something like object as a result.Mclean
But the data I want to display is an object of type "Product" and I need to display its name as the current selection. Please refer to the code snippet I provided in your answer. Otherwise its hard to match.Fiord
Okay. Try to use this: gist.github.com/Integral/5998949 Pass into options multiple: true and data object with id and value. I think that you must rename schemata to schema. If you have some json API I can post solution for ajax select2.Mclean
Oh, and you'll need to use Select2Rel type.Mclean
L
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]);
Lira answered 26/7, 2013 at 7:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.