select2 optgroups for Datatables Editor dropdown

select2 optgroups for Datatables Editor dropdown

EimantasEimantas Posts: 4Questions: 1Answers: 0
edited December 2015 in Free community support

Hey :) Thank you for this awesome lib! A little contribution to the community from me. I think that optgroups are not supported for Datatables Editor dropdown, so I had to make a little workaround to make it work (I'm using select2 for dropdowns). I thought that this post may be useful for someone in the future, so here's how I did it:

Declare this field as a simple text input:

            {
                label: "Ruleset:",
                name: "ruleset_to",
                options: {},
            },

Update the field value manually:

                var ruleset_dropdown = $('input', editor
                                                  .field('ruleset_to')
                                                  .node());

                var demodata = [{
                    text: "Optgroup 1",
                    children: [{
                        id: 1,
                        text: "Item One"
                    }, {
                        id: 2,
                        text: "Item two"
                    },]
                },{
                    text: "Optgroup 2",
                    children: [{
                        id: 3,
                        text: "Item 3"
                    }, {
                        id: 4,
                        text: "Item 4"
                    },]
                },]

                ruleset_dropdown.select2({
                    placeholder: "Select ruleset",
                    data: demodata
                });

Replies

  • ZakInterDevZakInterDev Posts: 51Questions: 16Answers: 0

    I found the opts to work, but your way is also required when doing ajax calls and updating the list. Obviously not all these are needed in your case, but may come in handy to other people, and there are more options found on select2s website :)

    {
                    label: "Ruleset:",
                    name: "ruleset_to",
                    type: "select2",
                    opts: {
                       placeholder: "Select ruleset", //(Doesn't work in IE - issue has been reported to the devs of select2)
                        allowClear: true,
                        multiple: true,
                        tags: true,
                        createTag: function (params) {
                            return {
                                id: params.term,
                                text: params.term,
                                newOption: true
                            };
                        }
                    }
    

    also you can access the select2 instance directly, via this code, to update your list.

    editor.field('ruleset_to').inst().select2({
          data: demodata
     });
    
    

    Hope these have been helpful :)

This discussion has been closed.