How does one set "selected" option using Editor.Select2 with AJAX options?

How does one set "selected" option using Editor.Select2 with AJAX options?

NettSiteNettSite Posts: 36Questions: 11Answers: 2

Hi,

I have been having some fun with Select2 and Editor, and am slowly making progress. My final hurdle is to set the "selected" option in the Select2 dropdowns (I have two).

I need to replace 'Caption' and 'ID' in the snippet below with the actual values of the text and the value of the option respectively when a record is edited.

"templateSelection": function (data) {
    console.log(data);  // Simply displays the placeholder so is not worth much
    return 'Caption' || 'ID';
 },

The text is displayed in the table, so I am hoping I can get it from there somehow, and the value is the actual item being edited in the Select2 control.

The complete code is as follows:

(function ($) {
    $(document).ready(function () {

        var filter;
        var job_titles;

        var editor = new $.fn.dataTable.Editor({
            ajax: {
                url: 'jobdescription',
                headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
            },
            table: '#indexTable',
            idSrc: 'id',
            fields: [
                {
                    "label": "Occupation Group:",
                    "name": "occgroup_id",
                    "type": "select2",
                    "data": "occgroup_id",
                    "opts": {
                        "templateSelection": function (data) {
                            console.log(data);
                            return 'Caption' || 'ID';
                        },
                        "minimumInputLength": 3,
                        "placeholder": 'Search for a Occupation Group',
                        "allowClear": true,
                        "ajax": {
                            "url": 'http://mibco.jobdesc.wnn/jobdesc/occgroup',
                            "dataType": 'json',
                            "delay": 250,
                            "cache": false,
                            "headers": {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                            "data": function (params) {
                                var query = {
                                    "q": params.term,
                                    "action": "select2",
                                    "field": "occupation_group",
                                    "filter": filter
                                };
                                return query;
                            },
                            "processResults": function (data, params) {
                                job_titles = data.results;
                                return {results: data.results};
                            }
                        }
                    },
                    "fieldInfo": ""
                }

                , {
                    "label": "Occupation Title:",
                    "name": "occtitle_id",
                    "type": "select2",
                    "data": "occtitle_id",
                    "opts": {
                        "templateSelection": function (data) {
                            console.log(data);
                            return 'Caption' || 'ID';
                        },
                        "minimumInputLength": 3,
                        "placeholder": 'Search for a Occupation Title',
                        "allowClear": true,
                        "ajax": {
                            "url": 'http://mibco.jobdesc.wnn/jobdesc/occtitle',
                            "dataType": 'json',
                            "delay": 250,
                            "cache": false,
                            "headers": {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                            "data": function (params) {
                                var query = {
                                    "q": params.term,
                                    "action": "select2",
                                    "field": "occupation_title",
                                    "filter": filter
                                };
                                return query;
                            },
                            "processResults": function (data, params) {
                                job_titles = data.results;
                                return {results: data.results};
                            }
                        }
                    },
                    "fieldInfo": ""
                }

                , {
                    "label": "Job Title:",
                    "name": "job_title",
                    "type": "text",
                    "fieldInfo": ""
                }

                , {
                    "label": "Description:",
                    "name": "description",
                    "type": "textarea",
                    "fieldInfo": ""
                }

                ,
                ,
            ]
        });

        // Set the value of the filter
        editor.dependent('occgroup_id', function (val) {
            filter = val;
        });

        // Set the value of the dependant fields
        editor.dependent('occtitle_id', function (val) {
            $.each(job_titles, function (key, result) {
                if (result.id == val) {
                    editor.val('job_title', result.text);
                    editor.val('description', result.desc);
                }
            });
        });

        // New record
        $('a.editor_create').on('click', function (e) {
            e.preventDefault();
            editor.create({
                title: 'Create new record',
                buttons: 'Add'
            });
        });

        // Edit record
        $('#indexTable').on('click', 'a.editor_edit', function (e) {
            e.preventDefault();
            editor.edit($(this).closest('tr'), {
                title: 'Edit record',
                buttons: 'Update'
            });
        });

        // Delete a record
        $('#indexTable').on('click', 'a.editor_remove', function (e) {
            e.preventDefault();
            editor.remove($(this).closest('tr'), {
                title: 'Delete record',
                message: 'Are you sure you wish to remove this record?',
                buttons: 'Delete'
            });
        });


        $('#indexTable').DataTable({
            processing: true,
            serverSide: true,
            ajax: 'jobdescription/?action=dte',
            responsive: true,
            columns: [
                {
                    "data": "job_title"
                },
                {
                    "data": "description"
                },
                {
                    "data": "occupation_group.occupation_group"
                },
                {
                    "data": "occupation_title.occupation_title"
                },
                {data: 'id',
                    className: "center nowrap",
                    bSortable: false,
                    render: function (data, type, row) {
                        return '<a href="" class="editor_edit"><button class="btn btn-primary">Edit</button></a> \n\
                                   <a href="" class="editor_remove"><button class="btn btn-danger">Delete</button></a>';
                    }
                }
            ],
            select: false,
            lengthChange: false
        });
    });
}(jQuery));

Answers

  • allanallan Posts: 61,891Questions: 1Answers: 10,143 Site admin

    Can you show me the data that jobdescription/?action=dte is loading please? Also what is the response of the Ajax call that Select2 is making?

    Thanks,
    Allan

  • NettSiteNettSite Posts: 36Questions: 11Answers: 2

    Hi Alan,

    Thanks for having a look. The data from jobdescription/?action=dte looks like this:

    {
        "draw": 1,
        "recordsTotal": 1,
        "recordsFiltered": 1,
        "data": [
            {
                "job_title": "Accountants",
                "description": "Analyze financial information and prepare financial reports to determine or maintain record of assets, liabilities, profit and loss, tax liability, or other financial activities within an organization.",
                "occgroup_id": "f24220fb-b411-11e7-b335-d8fee360fa7f",
                "occtitle_id": "f3940bdd-b411-11e7-b335-d8fee360fa7f",
                "created_at": "2017-10-23 12:14:03",
                "updated_at": "2017-10-23 13:08:31",
                "deleted_at": null,
                "id": "a8ecb739-b7eb-11e7-a25e-d8fee360fa7f",
                "occupation_group": {
                    "occupation_group": "Business &amp; Financial Operations",
                    "id": "f24220fb-b411-11e7-b335-d8fee360fa7f",
                    "deleted_at": null,
                    "created_at": "2017-10-18 16:51:18",
                    "updated_at": "2017-10-18 16:51:18"},
                "occupation_title": {
                    "occupation_title": "Accountants",
                    "description": "Analyze financial information and prepare financial reports to determine or maintain record of assets, liabilities, profit and loss, tax liability, or other financial activities within an organization.",
                    "occupation_group": "f24220fb-b411-11e7-b335-d8fee360fa7f",
                    "onet_id": null,
                    "id": "f3940bdd-b411-11e7-b335-d8fee360fa7f",
                    "created_at": "2017-10-18 16:51:18",
                    "updated_at": "2017-10-18 16:51:18",
                    "deleted_at": null
                }
            }
        ],
        "input": {
            "action": "dte",
            "draw": "1",
            "columns": [
                {
                    "data": "job_title",
                    "name": null,
                    "searchable": "true",
                    "orderable": "true",
                    "search": {"value": null, "regex": "false"}
                },
                {
                    "data": "description",
                    "name": null,
                    "searchable": "true",
                    "orderable": "true",
                    "search": {"value": null, "regex": "false"}
                },
                {
                    "data": "occupation_group.occupation_group", "name": null, "searchable": "true", "orderable": "true",
                    "search": {"value": null, "regex": "false"}
                },
                {
                    "data": "occupation_title.occupation_title", "name": null, "searchable": "true", "orderable": "true",
                    "search": {"value": null, "regex": "false"}
                },
                {
                    "data": "id", "name": null, "searchable": "true", "orderable": "false",
                    "search": {"value": null, "regex": "false"}
                }
            ],
            "order": [{"column": "0", "dir": "asc"}], "start": "0", "length": "10","search": {"value": null, "regex": "false"}, "_": "1508765163645"}
    }
    

    There is only one record in the database so far.

    The Select2 AJAX data, in this case for the "occgroup":

    {"results":[{"id":"f24220fb-b411-11e7-b335-d8fee360fa7f","text":"Business & Financial Operations","desc":null}]}
    

    That only happens when I actually do a search on the Select2 control, which is why I thought the best way would be to get the data from the "dte" response.

  • allanallan Posts: 61,891Questions: 1Answers: 10,143 Site admin

    My understanding of Select2 is that it should actually be showing the "Business & Financial Operations" text in its input field. From what you are saying, I guess that is not the case?

    Are you able to like to a test case showing the issue? If you can't make it public you can PM my by clicking my name above and then "Send message".

    Thanks,
    Allan

  • NettSiteNettSite Posts: 36Questions: 11Answers: 2

    Hi Alan,

    It is all currently on my local dev PC. I will set up an internet accessible instance and send you the link.

  • NettSiteNettSite Posts: 36Questions: 11Answers: 2

    The one thing I should emphasise is that the Select2 Ajax is not triggered when the Editor form is opened, but only when a search is done in the Select2 control.

    The data is available in the Datatables draw right from the start.

  • allanallan Posts: 61,891Questions: 1Answers: 10,143 Site admin

    This is what the Select2 documentation says about it.

    The Editor plug-in for Select2 should actually be doing that. Can you just check that the version you are using contains this line:

    if ( conf.opts && conf.opts.ajax && conf._input.find('options:attr(value["'+val+'"])').length === 0 ) {
    

    Thanks,
    Allan

  • NettSiteNettSite Posts: 36Questions: 11Answers: 2

    Hi Alan,

    It does indeed have that line at 191.

    I have set up an internet available instance, I will send you the details

This discussion has been closed.