Select2 field type - update() method - how to 'append' new options?

Select2 field type - update() method - how to 'append' new options?

SidetrackSidetrack Posts: 2Questions: 1Answers: 0

Hi- as per the select field type documentation, the update() method has an optional 'append' parameter to specify that the provided options should be added to the existing list of options, rather than replacing them. I'm trying to achieve the same effect with a Select2 field type.

I explored a solution using the inst() method to get the underlying Select2 object, and then using the native Select2 'append' method, but this resulted in duplicate options appearing the next time the Select2 is opened (I'm using the inline editing mode, in case that's relevant.) Any guidance appreciated- thanks in advance!


  • colincolin Posts: 8,661Questions: 0Answers: 1,449

    Could you link to the page, or create a test case, that shows the duplication, please. It'll help us to understand what you'retrying to do,


  • SidetrackSidetrack Posts: 2Questions: 1Answers: 0
    edited May 23

    Thanks for the reply, but I was able to adapt the existing update() function in the Select2 plugin to add an 'append' parameter mirroring that available for the normal select field type. Probably not the most elegant implementation, but it works! Code below in case this is of help to others.

    update: function (conf, data, append = false) {
            var val = _fieldTypes.select2.get(conf);
            if (append) {
                _fieldTypes.select2._appendOptions(conf, data);
            else {
                _fieldTypes.select2._addOptions(conf, data);
            // Restore null value if it was, to let the placeholder show
            if (val === null) {
                _fieldTypes.select2.set(conf, null);
            $(conf._input).trigger('change', { editor: true });
    _appendOptions: function (conf, opts) {
                var addOption = function (option) {
                    if (conf._input.find('option[value="' + option.value + '"]').length === 0) {
                            .attr('value', option.value)
                if ($.isArray(opts)) {
                    for (var i = 0, ien = opts.length; i < ien; i++) {
                else {
                //Re-sort the options list alphabetically
                var sortedOptions = conf._input.find('option').sort(function (a, b) {
                    return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
Sign In or Register to comment.