Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select2 4.0 AJAX pre-fill howto?

I've already read this, this, this and according to the documentation the most important here, but none of them work for me. I'm trying to use AJAX select2. I'm trying to make a generic "select" item.

So for all the elements that have a data-select2-json attribute, i apply a select2 with the ajax URL that is in the data-select2-json value.

$('[data-select2-json!=""][data-select2-json]').each(function() {
    var url = $(this).attr('data-select2-json');
    var pg_size = $(this).attr('data-select2-page-size') | 30;
    $(this).select2({
        language: language_code,
        tokenSeparators: [',', ' '],
        ajax: {
            url: url,
            dataType: 'json',
            delay: 300,
            data: function (params) {
                return {
                    q: params.term, // -> q=[search term]
                    page: params.page // -> page=[no page]
                };
            },
            processResults: function (data, params) {
                params.page = params.page || 1;
                console.log(data.items);
                return {
                    results: data.items,
                    pagination: {
                      more: (params.page * pg_size) < data.total
                    }
                };
            },
            cache: true
        },
        // let our custom formatter work
        escapeMarkup: function (markup) { return markup; },
        minimumInputLength: 1,
        templateResult: formatRepo,
        templateSelection: formatRepoSelection
    });
});

It works well!

works well

JSON the server sends is always formatted like this:

{"items":
    [{"item": "Fran\u00e7ais", "id": 1},
     {"item": "Finlandais", "id": 5},
     {"item": "Chinois simplifi\u00e9", "id": 15}
    ],
"total": 3}

It's very close to the AJAX sample you can find in the documentation. My problem is AJAX initiatilize: I want either to add the values in the HTML:

<select multiple="multiple" class="form-control"
        data-select2-json="/fr/chez-moi/tags/langues"
        multiple="multiple"
        name="known_languages">
    <option value="1" selected="selected">Français</option>
    <option value="2" selected="selected">Chinois simplifié</option>
</select>

and then initialize with select2 (= the code $(this).select2({.. above ) but this doesnt work and gives me blank values:

blank value

NB: the solution here given by Kevin Brown doesn't work either and gives me exactly the same result.

The other solution is to ask in AJAX to the URL with a parameter like "&init=1" (or something like that) so the server will send results with added parameters like checked: true for each value, and I will call select2 with those values.

Nothing clear in the documentation on how to pre-fill select2. How should I do?

Here are my other functions:

function item_or_text(obj) {
    if (typeof(obj.item)!='undefined') {
        return (obj.item.length ? obj.item : obj.text);
    }
    return obj.text;
}

function formatRepo(data) {
    if (data.loading) return data.text;
    var markup = item_or_text(data);
    console.log('formatRepo', data, markup);
    return markup;
}

function formatRepoSelection(item) {
    var retour = item_or_text(item);
    console.log('formatRepoSelection', item, item.item, retour);
    return retour;
}
like image 363
Olivier Pons Avatar asked Oct 18 '22 19:10

Olivier Pons


1 Answers

I created a working example on jsfiddle using the example code provided on the Select2 Examples page. I just had to change their example select tag to accept multiple like yours:

<select multiple="multiple" ...

I also added a second default selected option:

<option value="3620194" selected="selected">select2/select2</option>
<option value="317757" selected="selected">Modernizr/Modernizr</option>

If you have a look at the fiddle, you will see it working how you would like yours to work.

You did not include the code for your templateSelection: formatRepoSelection method. My guess is that method is the cause of your problem. The code used on the examples page is:

function formatRepoSelection(repo) {
  return repo.full_name || repo.text;
}

Although I have no idea what your formatRepoSelection code is, I think if you change it to something like the following, your issue will be solved:

function formatRepoSelection(repo) {
  return repo.item;
}
like image 165
Fraser Crosbie Avatar answered Oct 21 '22 16:10

Fraser Crosbie