Search code examples
jquery-select2jquery-select2-4

Error with Data Adapter with select2 4


I am trying to use more than 10000 datas in my combobox and I have this code

$.fn.select2.amd.define('select2/data/customAdapter',[
        'select2/data/array',
        'select2/utils'
    ],
    function (ArrayAdapter, Utils) {

        function CustomDataAdapter ($element, options) {
            CustomDataAdapter.__super__.constructor.call(this, $element, options);
        }
        Utils.Extend(CustomDataAdapter, ArrayAdapter);

        CustomDataAdapter.prototype.query = function (params,callback) {
            console.log(params);
           var pageSize,
                    results;
                    pageSize = 20;
                    results  = _.filter(content, function (e) {
                        return (params.term === "" || e.text.toUpperCase().indexOf(params.term.toUpperCase()) >= 0);
                 });
                 console.log(results);
                 callback({
                    results: results.slice((params.page - 1) * pageSize, params.page * pageSize),
                    // retrieve more when user hits bottom
                    more   : results.length >= params.page * pageSize
                });
        };

        return CustomDataAdapter;
    }
);

var customAdapter=$.fn.select2.amd.require('select2/data/customAdapter');
    objCmb.select2({
        allowClear: true, 
        disabled: dis, 
        placeholder: Empty, 
        data: content, 
        formatLoadMore   : 'Loading more...',
        dataAdapter:customAdapter

    });

when I use the select2 this error appear

TypeError: params.term is undefined

...ms.term === "" || e.text.toUpperCase().indexOf(params.term.toUpperCase()) >= 0)


Solution

  • The problem is that when someone focuses the select2 control, there's no really a term, so the params object is empty (e.g. {}). You can see this in this JsFiddle (just try to search for something).

    If you want to get rid of that error, you can modify your custom query function to account for that:

    CustomDataAdapter.prototype.query = function (params, callback) {
        var pageSize, results;
        pageSize = 20;
        results = _.filter(content, function (e) {
            return (params.term == null || params.term === "" || e.text.toUpperCase().indexOf(params.term.toUpperCase()) >= 0);
                 // ^^^^^^^^^^^^^^^^^^^
        });
        callback({
            results: results.slice((params.page - 1) * pageSize, params.page * pageSize),
            more: results.length >= params.page * pageSize
        });
    };
    

    This will be working as you'd expect it to (modified fiddle).

    I would also like to note that your code example does not include the select population with items, so it's not present in the above fiddles either.