Select form control loses it's options after submit

Select form control loses it's options after submit

NettSiteNettSite Posts: 36Questions: 11Answers: 2

Link to test case: Currently on my local PC, but I can make it available on a web server if necessary.
Debugger code (debug.datatables.net): I can't run that:

Access to XMLHttpRequest at 'https://api.datatables.net/versions/feed' from origin 'http://cpdtraining' has been blocked by CORS policy: Request header field x-csrf-token is not allowed by Access-Control-Allow-Headers in preflight response.

Error messages shown: None
Description of problem: I have a editor from which has a Select2 dropdown. It initialises perfectly, but can only be used once to add or update a record. After that, it no longer has any options. This happens whether it is a "select" or a "select2" type of field.

The select2 has opt tags set to true, but not doing that makes no difference.

This is my script:

(function (window, $) {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': 'FmVEOOeSJMSizrGUMFkX1ivZeDtZDX8BO7YVpBnh'
        }
    });
    window.LaravelDataTables = window.LaravelDataTables || {};
    var editor = window.LaravelDataTables["indexTable-editor"] = new $.fn.dataTable.Editor({
        "instance": "editor",
        "idSrc": "id",
        "fields": [{
            "name": "development_area",
            "label": "Development Area",
            "type": "select2",
            "options": {
                "Use of derivatives": "Use of derivatives",
                "Reporting fundamentals": "Reporting fundamentals",
                //  more options
                "The financial strategy": "The financial strategy"
            },
            "className": "wrap",
            "title": "Development Area",
            "opts": {
                "tags": true
            }
        }, {
            "name": "motivation",
            "label": "Motivation",
            "type": "tinymce"
        }, {
            "name": "completed",
            "label": "Completed",
            "type": "radio",
            "options": {
                " No": 0,
                "Yes": 1
            },
            "unselectedValue": 0,
            "className": "text-center",
            "createdCell": function (td, cellData, rowData, row, col) {
                $(td).css('text-align', 'center');
                if (cellData < 1) {
                    $(td).css('color', 'red');
                    $(td).html('<li class=material-icons>report</li>');
                } else {
                    $(td).css('color', 'green');
                    $(td).html('<li class=material-icons>check_box</li>');
                }
            }
        }, {
            "name": "annual_plan_id",
            "label": "Annual Plan Id",
            "type": "hidden",
            "visible": false,
            "title": "Annual Plan",
            "data": "annual_plan.year"
        }, {
            "name": "id",
            "label": "Id",
            "type": "hidden"
        }],
        "formOptions": {
            "main": {
                "buttons": true,
                "focus": 0,
                "message": true,
                "onBackground": "blur",
                "onBlur": "close",
                "onComplete": "close",
                "onEsc": "close",
                "onFieldError": "focus",
                "onReturn": "submit",
                "submit": "all",
                "title": "Submit",
                "drawType": false,
                "scope": "row"
            }
        },
        "i18n": {
            "create": {
                "button": "New",
                "title": "New",
                "submit": "Create"
            },
            "edit": {
                "button": "Edit",
                "title": "Edit",
                "submit": "Update"
            },
            "remove": {
                "button": "Delete",
                "title": "Delete",
                "submit": "Delete",
                "confirm": {
                    "_": "Are you sure you wish to delete 0 rows?",
                    "1": "Are you sure you wish to delete this row?"
                },
                "multi": {
                    "title": "Multiple values",
                    "info": "The selected items contain different values for this input. To edit and set all items for this input to the same value, click or tap here, otherwise they will retain their individual values.",
                    "restore": "Undo changes",
                    "noMulti": "This input can be edited individually, but not part of a group."
                }
            }
        },
        "display": "envelope",
        "table": "#indexTable",
        "ajax": "http:\/\/cpdtraining\/development-area\/85cefe13-6b85-40a1-bf35-f5e24ba2473f"
    });

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

    // Delete a record
    $('#indexTable').on('click', 'button.editor_remove', function (e) {
        e.preventDefault();
        console.log('Deleting');
        editor.remove($(this).closest('tr'), {
            title: 'Delete record',
            message: 'Are you sure you wish to remove this record?',
            buttons: 'Delete'
        });
    });
    
    window.LaravelDataTables["indexTable"] = $("#indexTable").DataTable({
        "serverSide": true,
        "processing": true,
        "ajax": {
            "url": "http:\/\/cpdtraining\/development-area\/85cefe13-6b85-40a1-bf35-f5e24ba2473f",
            "type": "GET",
            "data": function (data) {
                for (var i = 0, len = data.columns.length; i < len; i++) {
                    if (!data.columns[i].search.value) delete data.columns[i].search;
                    if (data.columns[i].searchable === true) delete data.columns[i].searchable;
                    if (data.columns[i].orderable === true) delete data.columns[i].orderable;
                    if (data.columns[i].data === data.columns[i].name) delete data.columns[i].name;
                }
                delete data.search.regex;
            }
        },
        "columns": [{
            "data": "id",
            "name": "id",
            "title": "Id",
            "orderable": false,
            "searchable": false,
            "visible": false
        }, {
            "data": "development_area",
            "name": "development_area",
            "title": "Development Area",
            "orderable": true,
            "searchable": true,
            "type": "select2",
            "visible": true,
            "width": "30%",
            "className": "wrap",
            "opts": {
                "tags": true
            }
        }, {
            "data": "motivation",
            "name": "motivation",
            "title": "Motivation",
            "orderable": true,
            "searchable": true,
            "type": "tinymce",
            "visible": true,
            "width": "30%"
        }, {
            "data": "completed",
            "name": "completed",
            "title": "Completed",
            "orderable": true,
            "searchable": true,
            "type": "radio",
            "visible": true,
            "unselectedValue": 0,
            "className": "text-center",
            "createdCell": function (td, cellData, rowData, row, col) {
                $(td).css('text-align', 'center');
                if (cellData < 1) {
                    $(td).css('color', 'red');
                    $(td).html('<li class=material-icons>report</li>');
                } else {
                    $(td).css('color', 'green');
                    $(td).html('<li class=material-icons>check_box</li>');
                }
            }
        }, {
            "data": "annual_plan.year",
            "name": "annual_plan_id",
            "title": "Annual Plan",
            "orderable": true,
            "searchable": true,
            "type": "hidden",
            "visible": false
        }, {
            "data": "id",
            "name": "action",
            "title": "Action",
            "orderable": false,
            "searchable": false,
            "className": "text-center",
            "render": function (data, type, full, meta) {
                return "<button class='btn-sm btn-primary editor_edit' type='button' style='width:116px;'>Edit</button>&nbsp;<button class='btn-sm btn-danger editor_remove' type='button' style='width:116px;'>Delete</button>&nbsp;<a href='/learning-activity/" + data + "'><button class='btn-sm btn-primary' type='button'>Activities <li class='material-icons' style='font-size:0.8em;'>arrow_forward</li></button></a>";
            }
        }],
        "responsive": true,
        "dom": "Bfrtip",
        "select": {
            "style": "os"
        },
        "order": [
            [1, "desc"]
        ],
        "buttons": [{
            "extend": "create",
            "editor": editor,
            "className": "btn-success"
        }]
    });
})(window, jQuery);

This question has accepted answers - jump to:

Answers

  • NettSiteNettSite Posts: 36Questions: 11Answers: 2
    Answer ✓

    OK, so I am just dumb. I had a "createdCell" thing in the editor code as well as the table code, where it obviously shouldn't have been - a victim of my own laziness.

    All fixed now.

  • allanallan Posts: 63,213Questions: 1Answers: 10,415 Site admin
    Answer ✓

    Thanks for posting back. Good to hear you’ve got it working now.

    Allan

  • NettSiteNettSite Posts: 36Questions: 11Answers: 2
    edited August 2020

    I was wrong, this wasn't fixed, or working....

    Actually, it's worse. It seems that an editor may be opened once, and it works perfectly, but then it stops working. On the next open, the Select2 field no longer works (I thought it lost it's options, but I was wrong about that as well), and the date fields no longer have date pickers.

    Help would be greatly appreciated, there are no error or any other messages that I can see.

    This is an example of my latest code:

  • NettSiteNettSite Posts: 36Questions: 11Answers: 2
    edited August 2020

    Code:

    (function (window, $) {
        $.ajaxSetup({ headers: { "X-CSRF-TOKEN": "QTMhm01as0cWUkeDLNCUU40BeRdmTiXtCakPvEql" } });
        window.LaravelDataTables = window.LaravelDataTables || {};
        var editor = (window.LaravelDataTables["indexTable-editor"] = new $.fn.dataTable.Editor({
            instance: "editor",
            idSrc: "id",
            fields: [
                {
                    name: "activity",
                    label: "Activity",
                    type: "select2",
                    options: {
                        "Internal training/workshop": "Internal training/workshop",
                        // options removed to shorten code for posting
                        "Online learning": "Online learning",
                    },
                    opts: { tags: true },
                },
                {
                    name: "description",
                    label: "Description",
                    type: "tinymce",
                    opts: { plugins: "lists", menubar: false, toolbar: "undo redo | formatselect | bold italic | alignleft aligncenter alignright alignjustify | numlist bullist | outdent indent | ", elementpath: false },
                },
                { name: "potential_date", label: "Potential Date", type: "datetime", format: "DD/MM/YYYY", className: "date-field" },
                { name: "actual_date", label: "Actual Date", type: "datetime", format: "DD/MM/YYYY", className: "date-field" },
                { name: "hours", label: "Hours", type: "text", attr: { type: "number" }, className: "number-field" },
                {
                    name: "reflection",
                    label: "Reflection",
                    type: "tinymce",
                    opts: { plugins: "lists", menubar: false, toolbar: "undo redo | formatselect | bold italic | alignleft aligncenter alignright alignjustify | numlist bullist | outdent indent | ", elementpath: false },
                    visible: false,
                },
                { name: "completed", label: "Completed", type: "hidden", className: "text-center" },
                { name: "development_area_id", label: "Development Area Id", type: "hidden", visible: false, title: "Development Area" },
                { name: "id", label: "Id", type: "hidden" },
            ],
            formOptions: {
                main: {
                    buttons: false,
                    focus: 0,
                    message: true,
                    onBackground: "blur",
                    onBlur: "close",
                    onComplete: "close",
                    onEsc: "close",
                    onFieldError: "focus",
                    onReturn: "submit",
                    submit: "all",
                    title: "Submit",
                    drawType: false,
                    scope: "row",
                },
            },
            i18n: {
                create: { button: "New", title: "New", submit: "Create" },
                edit: { button: "Edit", title: "Edit", submit: "Update" },
                remove: {
                    button: "Delete",
                    title: "Delete",
                    submit: "Delete",
                    confirm: { _: "Are you sure you wish to delete 0 rows?", "1": "Are you sure you wish to delete this row?" },
                    multi: {
                        title: "Multiple values",
                        info: "The selected items contain different values for this input. To edit and set all items for this input to the same value, click or tap here, otherwise they will retain their individual values.",
                        restore: "Undo changes",
                        noMulti: "This input can be edited individually, but not part of a group.",
                    },
                },
            },
            display: "envelope",
            scripts: "removed to shorten for posting"
            table: "#indexTable",
            ajax: "http://cpdtraining/learning-activity/d526da99-24b7-4fbc-9dd8-914adb635df5",
        }));
        // Create a new record
        $("a.editor_create").on("click", function (e) {
            e.preventDefault();
            editor.create({
                title: "Create new record",
                buttons: [
                    {
                        text: "Cancel",
                        className: "btn btn-default",
                        action: function () {
                            this.close();
                        },
                    },
                    {
                        text: "Add",
                        className: "btn btn-primary",
                        action: function () {
                            this.submit();
                        },
                    },
                ],
            });
        }); // Edit a record
        $("#indexTable").on("click", "button.editor_edit", function (e) {
            e.preventDefault();
            editor.edit($(this).closest("tr"), {
                title: "Edit record",
                buttons: [
                    {
                        text: "Cancel",
                        className: "btn btn-default",
                        action: function () {
                            this.close();
                        },
                    },
                    {
                        text: "Update",
                        className: "btn btn-primary",
                        action: function () {
                            this.submit();
                        },
                    },
                ],
            });
        }); // Delete a record
        $("#indexTable").on("click", "button.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: [
                    {
                        text: "Cancel",
                        className: "btn btn-default",
                        action: function () {
                            this.close();
                        },
                    },
                    {
                        text: "Delete",
                        className: "btn btn-danger",
                        action: function () {
                            this.submit();
                        },
                    },
                ],
            });
        });
        window.LaravelDataTables["indexTable"] = $("#indexTable").DataTable({
            serverSide: true,
            processing: true,
            ajax: {
                url: "http://cpdtraining/learning-activity/d526da99-24b7-4fbc-9dd8-914adb635df5",
                type: "GET",
                data: function (data) {
                    for (var i = 0, len = data.columns.length; i < len; i++) {
                        if (!data.columns[i].search.value) delete data.columns[i].search;
                        if (data.columns[i].searchable === true) delete data.columns[i].searchable;
                        if (data.columns[i].orderable === true) delete data.columns[i].orderable;
                        if (data.columns[i].data === data.columns[i].name) delete data.columns[i].name;
                    }
                    delete data.search.regex;
                },
            },
            columns: [
                { data: "id", name: "id", title: "Id", orderable: false, searchable: false, visible: false },
                { data: "activity", name: "activity", title: "Activity", orderable: true, searchable: true, type: "select2", visible: true, width: "25%" },
                { data: "description", name: "description", title: "Description", orderable: true, searchable: true, type: "tinymce", visible: true, width: "25%" },
                { data: "potential_date", name: "potential_date", title: "Potential Date", orderable: true, searchable: true, type: "date", visible: true, className: "date-field" },
                { data: "actual_date", name: "actual_date", title: "Actual Date", orderable: true, searchable: true, type: "date", visible: true, className: "date-field" },
                { data: "hours", name: "hours", title: "Hours", orderable: true, searchable: true, type: "number", visible: true, className: "number-field" },
                { data: "reflection", name: "reflection", title: "Reflection", orderable: true, searchable: true, type: "tinymce", visible: false },
                {
                    data: "completed",
                    name: "completed",
                    title: "Completed",
                    orderable: true,
                    searchable: true,
                    type: "hidden",
                    visible: true,
                    className: "text-center",
                    createdCell: function (td, cellData, rowData, row, col) {
                        $(td).css("text-align", "center");
                        if (cellData < 1) {
                            $(td).css("color", "red");
                            $(td).html('<span style="padding:10px;" class=material-icons>report</span>');
                        } else {
                            $(td).css("color", "green");
                            $(td).html('<span style="padding:10px;" class=material-icons>check_box</span>');
                        }
                    },
                },
                { data: "development_area_id", name: "development_area_id", title: "Development Area", orderable: true, searchable: true, type: "hidden", visible: false },
                {
                    data: "id",
                    name: "action",
                    title: "Action",
                    orderable: false,
                    searchable: false,
                    className: "text-center",
                    render: function (data, type, full, meta) {
                        return "<button class='btn btn-primary editor_edit' type='button' style='padding:12px;'><span class='material-icons'>create</span></button>&nbsp;<button class='btn btn-danger editor_remove' type='button' style='padding:12px;'><span class='material-icons'>delete</span></button>&nbsp;";
                    },
                },
            ],
            responsive: true,
            dom: "Bfrtip",
            select: { style: "os" },
            order: [[1, "desc"]],
        });
    })(window, jQuery);
    
  • allanallan Posts: 63,213Questions: 1Answers: 10,415 Site admin

    You mentioned it would be possible to make it accessible on the web. Could you do so please? I'll be able to help debug it then.

    Allan

  • NettSiteNettSite Posts: 36Questions: 11Answers: 2

    Hi Allan,

    Thank you!

    You will see the problem at

    https://cpd.nettsite.co.za/learning-activity/bf0c9fc4-5129-4f9f-89fa-3d0944bf1cf1
    
    • just click a pencil to open an editior, which works perfectly, once. After that, the select and the date pickers no longer work at all. There are no mean error messages in the console that I can see.

    Log in as william@nettsite.co.za,

    6RssAu1@m!S0
    

    It's not a live site.

  • NettSiteNettSite Posts: 36Questions: 11Answers: 2

    Hi Allan,

    Thank you!

    You will see the problem at https://cpd.nettsite.co.za/learning-activity/bf0c9fc4-5129-4f9f-89fa-3d0944bf1cf1 - just click a pencil to open an editior, which works perfectly, once. After that, the select and the date pickers no longer work at all. There are no mean error messages in the console that I can see.

    Log in as william@nettsite.co.za, 6RssAu1@m!S0

    It's not a live site.

  • allanallan Posts: 63,213Questions: 1Answers: 10,415 Site admin
    Answer ✓

    Hi,

    Thanks! Could you possibly try commenting out the display: 'envelope', part please? I'm wondering if it is being caused by an over zealous event handler removal.

    Allan

  • NettSiteNettSite Posts: 36Questions: 11Answers: 2

    Hi Allan,

    Great joy and jubilation! That was it. I will have to live without the envelope.

    Will.

This discussion has been closed.