0

How to define select2 default AJAX value?

I've tried many but still cannot get it working.

Below is my code:

$("#qrcode_group_rowid").select2({
    ajax: {
        url: "app/qrcode/qrcode_group_select_service.php",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                q: params.term, // search term
                page: params.page
            };
        },
        processResults: function (data, params) {
            params.page = params.page || 1;

            return {
                results: data.items,
                pagination: {
                    more: (params.page * 50) < data.total_count
                }
            };
        },
        cache: true
    },
    placeholder: 'Please select',
    escapeMarkup: function (markup) { return markup; },
    minimumInputLength: 0,
    templateResult: formatRepo,
    templateSelection: formatRepoSelection
});
function formatRepo (json) {
    if (json.loading) {
        return json.text;
    }
    var markup = json.group_name;
    return markup;
}
function formatRepoSelection (json) {
    return json.group_name;
}

and my JSON data:

{
"total_count": 897,
"items": [{"id": 901,"group_name": "TEST25-117"},{"id": 1,"group_name": "TEM117"}]
}

What am I doing wrong and how can I fix it?

beaver
  • 17,333
  • 2
  • 40
  • 66
net8bits
  • 1
  • 2
  • Have you checked this post https://stackoverflow.com/questions/30316586/select2-4-0-0-initial-value-with-ajax? – beaver Feb 26 '18 at 14:09

1 Answers1

0

You should send the following information in the PHP method (there may be a limitation of working with the IP address in eloquent)

/** @var Collection $btsNodes */
    $btsNodes = BtsNode::where('node_code' , 'like' , '%'.$request->get('q').'%')
                ->get(['node_code']);
         //       ->toArray();
    $items = $btsNodes->map(function ($item){
        return [
            'id' => $item['node_code'],
            'node_code' => $item['node_code']
        ];
    });

    return ['items' => $items];