Inline Editor - Select2 sending empty values

Inline Editor - Select2 sending empty values

FraserHFraserH Posts: 3Questions: 1Answers: 0

I am using the select2 intergration with inline editing. I am using Patch requests to preform partial updates to my data.
I notice the specific select2 field is always sent with this request regardless of whether this field has been modified or not.

Is there a way of emitting this field from being sent unless a change has been made, or if that is not possible setting the select2 selected object to that of the data pulled back by the datatables.

below is my datatables code

    var interface_mapper_datatable = $('#interface_mapper_table').DataTable({
        dom: '<"top">rt<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7 dataTables_pager"<"pull-right"lp>>><"clear">',
        //dom: 'Bfrtip',
        // columns definition
        columnDefs: [
            {className: "text-center", targets: "_all"},
            {className: "text-left", targets: 0},


            {targets: 0, visible: false,},
            {targets: 1, visible: false,},
            {
                targets: 4,
                "createdCell": function (td, cellData, rowData, row, col) {
                    if (cellData < 1) {
                        $(td).css('color', 'red')
                    }
                }


            }
        ],
        columns: [
            {data: "uuid"},
            {data: "switch"},
            {data: "existing_switch_name"},
            {data: "interface"},
            {data: "speed"},
            {data: "mode"},
            {data: "description"},
            {data: "destination_interface_name", editField: "destination_interface"}
        ],
        pageLength: 10,
        responsive: true,
        rowId: 'uuid',
        order: [[1, "desc"]],
        "lengthMenu": [[10, 20, 50, -1], [10, 20, 50, "All"]],
        language: {
            lengthMenu: " _MENU_"
        },
        select: true,
        buttons: [
            {extend: 'edit', editor: editor},
            {extend: 'remove', editor: editor}
        ]
    });

    var editor = new $.fn.dataTable.Editor({
        // ajax:  '/api/v1/migration-tool/switch-mapper/editor/?format=datatables',
        ajax: {
            create: {
                type: 'POST',
                url: '/api/v1/migration-tool/interfaces'
            },
            edit: {
                type: 'PATCH',
                url: '/api/v1/migration-tool/interfaces/_id_'
            },
            remove: {
                type: 'DELETE',
                url: '/api/v1/migration-tool/interfaces/_id_',
                deleteBody: false
            }
        },
        table: '#interface_mapper_table',
        idSrc: 'uuid',
        fields: [
            // {label: 'uuid', name: 'uuid',},
            // {label: 'switch', name: 'switch'},
            // {label: 'existing_switch_name', name: 'existing_switch_name'},
            // {label: 'interface', name: 'interface'},
            // {label: 'speed', name: 'speed',},
            // {label: 'mode', name: 'mode'},
            {label: 'description', name: 'description'},
        ]
    });

    editor.add({
        "label": "destination_interface_name:",
        "name": "destination_interface",
        "type": "select2",
        "initialValue": true,
        "opts": {
            allowClear: true,
            CloseOnSelect: false,
            cache: true,
            placeholder: "Select Interface",
            ajax: {
                url: (function () {
                    var data = $('#endpoint').select2('data')[0]['id'].split('_').pop();
                    var url = "/api/v1/aci/fabric-node-interfaces?interface=&switch__site_id__uuid=" + data;
                    console.log(url);
                    return url
                }),
                dataType: 'json',
                delay: 250,
                data: function (params) {
                    // console.log(params.term);
                    return {
                        switch__node_name: params.term, // search term

                    };
                },
                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;
                    var formatted_data = [];
                    for (i = 0; i < data.results.length; i++) {
                        formatted_data.push(
                            {
                                'id': data.results[i].uuid,
                                'text': data.results[i].interface_name,
                            }
                        )
                    }
                    return {
                        results: formatted_data,
                    };
                },


            },
            escapeMarkup: function (markup) {
                return markup;
            },
        }
    });

i have tried to setting it as per the select2 documentation [here](https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2 "here") without any luck.

    // Update select2 selection based on row.
    interface_mapper_datatable.on('select', function (e) {
        var data = interface_mapper_datatable.row({selected: true}).data();
        var destination_interface = data.destination_interface;
        // Fetch the preselected item, and add to the control
        var editor_select2 = $('#DTE_Field_destination_interface');
        $.ajax({
            type: 'GET',
            url: '/api/v1/aci/fabric-node-interfaces/' + destination_interface
        }).then(function (data) {
            // create the option and append to Select2
            var option = new Option(data.interface_name, data.uuid, true, true);
            var formatted_data =
                {
                    'id': data.uuid,
                    'text': data.interface_name,
                };
            editor_select2.append(option).trigger('change');


            // manually trigger the `select2:select` event
            editor_select2.trigger({
                type: 'select2:select',
                params: {
                    data: formatted_data
                }
            });
        });
    });

PATCH request when interface is modified:
data[6ffb1ff6-7572-4a34-81f4-d8213d6df0b2][destination_interface]: 7f9a3a5d-c244-4f69-97fb-3db5123e95aa
action: edit

PATCH request when only the description field is modified:
data[6ffb1ff6-7572-4a34-81f4-d8213d6df0b2][description]: PDC-ENC3-PRDVC1-X2R
data[6ffb1ff6-7572-4a34-81f4-d8213d6df0b2][destination_interface]:
action: edit

Any help is appricated.

Answers

  • allanallan Posts: 63,691Questions: 1Answers: 10,500 Site admin

    Editor will submit the parameters for the fields which it finds the value has changed.

    So what we need to determine here is why the value for the Select2 field is changing (or why Editor thinks it has changed). Are you able to give me a link to your page so I can trace that through?

    If not, when the form is in edit mode, in your browser's console, what do you get if you do:

    console.log( editor.field('destination_interface').val(), typeof editor.field('destination_interface').val() );
    

    ?

    Thanks,
    Allan

  • FraserHFraserH Posts: 3Questions: 1Answers: 0

    Thanks for thew quick response, let me try and get a page available publicly, in the mean time please see below.

    Just putting in the above i get the following:

    console.log( editor.field('destination_interface').val(), typeof editor.field('destination_interface').val() );

    VM7442:1 Uncaught ReferenceError: editor is not defined
    at <anonymous>:1:14

    if i try and get the Editor instance manually from the console i get the following:
    var editor = $('#interface_mapper_table').dataTable.Editor()

    editor.field('destination_interface').val(), typeof editor.field('destination_interface').val()
    "object"
    editor.field('destination_interface').val()
    null

    editor.field('description').val(), typeof editor.field('description').val()
    "string"
    editor.field('description').val()
    "LG-NPES-DFS03_HB"

    below is an example of what should be shown for that row:

  • FraserHFraserH Posts: 3Questions: 1Answers: 0

    to add to this if i go into the field and re-select the value that was orignally in the table it showd the following:

    console.log( editor.field('destination_interface').val(), typeof editor.field('destination_interface').val() );
    VM8389:1 1a4e3ff4-1d36-4bb8-b914-ea245536976b string

    that value is the correct string for the uuid which would be sent in a patch requiest.

    If i reselect the same value that shows before the inline editing is launched and press enter the editor correctly knows not to send a patch request as this value is unchanged.

  • flyshellflyshell Posts: 9Questions: 3Answers: 0

    same issue too.

    in plugin #120, if the ajax returns well, you should be fine.

    for inline,
    we simply ignore ajax, and make the select one option for setting value to work

    below is my version:

    if (this.s.mode == 'inline' && val) {
    $('<option>', {value: val, text: val}).appendTo(conf._input);
    needAjax = false;
    }

    if ( needAjax && val ) {

Sign In or Register to comment.