Search code examples
jquerydatatablesjquery-select2jquery-datatables-editor

Auto selecting Select2 from JSON request: using Datatables Editor


I'm using select2 as a typeahead sort of thing: as the user types, the results are populated based on the changing input. I use templateResult to customize the search results with images, buttons, etc. templateSelection will return to the select2 input just certain parts of the ajax JSON.

It works great.

I am using datatables Editor now to show the form. As part of Editor, when the form opens in edit mode, the same URL ajax request based on my code below will add initialValue=true and value="something" parameters to the URL.

On the AJAX php page, I catch if initialValue = true and then respond with the JSON data that corresponds to the value that is sent.

Here's my select2:

{
   "label": "Attach to Contact:",
   "name": "assigned_to_contact_id",
   "type": "select2",
        "opts": {
             value: "",
             initialValue: true,
             ajax: {
                    url: "ajax_get_json.php?what=company_autocomplete_contacts",
                    dataType: 'json',
                    delay: 250,
                    data: function (params) {
                        return {
                            query: params.term, // search term
                            page: params.page
                        };
                    },
                    processResults: function (data, params) {
                        // parse the results into the format expected by Select2
                        // since we are using custom formatting functions we do not need to
                        // alter the remote JSON data, except to indicate that infinite
                        // scrolling can be used                            
                        params.page = params.page || 1;

                        return {
                            results: data,
                            pagination: {
                                more: (params.page * 30) < data.total_count
                            }
                        };
                    },
                    cache: true
                },
                escapeMarkup: function (markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 1,
                templateResult: formatResults_editor,
                templateSelection: formatResultsSelection_editor,
                allowClear: true,
                placeholder: {
                    "id": "",
                    "text": "(Searching all locations)"
                }
            }
 }

Here are my format functions:

function formatResults_editor(results) {

    if (results.loading) {
        return "Searching...";
    }

    //set image to contact pic
    var image = '';

    if (results.no_contact_pic_requested == 'Y') {
        image = 'company_specific_files/contacts_images/no_pic_requested.png';
    } else {
        image = 'company_specific_files/contacts_images/' + results.company_id + '/' + results.id + '/' + 'webcam.jpg';
        //check to see if the pic exists, else set default image
        $.ajax({
            type: "POST",
            async: false,
            url: 'company_specific_files/contacts_images/' + results.company_id + '/' + results.id + '/' + 'webcam.jpg',
            error: function (response, status, xhr) {
                //if no image present, use default image
                image = 'company_specific_files/contacts_images/blank_avatar.png';

            },
            success: function (response, status, xhr) {
                //this is how I see if there's an image:  check the content-type response from ajax call. Make sure ajax is not async to work
                var ct = xhr.getResponseHeader("content-type") || "";

                if (ct == "image/jpeg") {
                    image = 'company_specific_files/contacts_images/' + results.company_id + '/' + results.id + '/' + 'webcam.jpg';
                } else {
                    image = 'company_specific_files/contacts_images/blank_avatar.png';
                }

            }
        });
    }

    var markup = "<div class='clearfix'><img style='float:left; padding-right: 5px' class='img-responsive' height='50' width='50' src='" + image + "'>" + ' ' + results.label + "</div>";
    return markup;

}

function formatResultsSelection_editor(results) {


    if (results.id === '') {
        return '(Searching all locations)'; //placeholder added this way since using ajax per docs.
    }

    return results.contact_name + ' ' + results.birthdate;

}

When the user types/search for a name in the select2, everything works fine: the value is populated, the results are formatted in the dropdown box, the result is shown afterselect in the select2 input fine.

Now if the editor opens and it populates the value of the select2, the AJAX request looks like this:

ajax_get_json.php?what=company_autocomplete_contacts&initialValue=true&value=%224258%22  

... and the response looks like this from that page:

{"id":"1","text":"sample text","location":"Bayview","contact_name":"Mark","birthdate":"2010-05-28","label":"Mark from Bayview","value":"22","location_id":"4322","company_id":"432342","no_contact_pic_requested":"N"}

So why doesn't the select2 autopopulate with the JSON response label like it would if it were selected from templateSelection?

The placeholder when there's an initial value still says "Searching..." when the form opens in edit mode, when it really should say 'Mark (2010-05-28)' as it does if a user searches for it and selects the templateResult option.

This is as far as I've got and can't seem to make any more progress.


Solution

  • If anyone ever comes across this:

    This has to do with Datatables Editor, I found.

    I cannot use templateSelection. I format the results with an id and text. From there, it will populate accordingly.