Pls help to figure out why editor can't determine field from source when I click on field

Pls help to figure out why editor can't determine field from source when I click on field

TurumTurum Posts: 5Questions: 1Answers: 0
edited June 18 in Editor

Please help me to identify the problem. When I try to edit a cell in the "compensation" column in the "DetailedIncidentsTable" table, I get the error Uncaught Unable to determine field from source automatically. Please specify the field name. For more information, please refer to https://datatables.net/tn/11 although judging by the log output, the click event selects the desired cell. My debug code is: upuzeg. I apologize if it's confusing, I'll try to answer questions if there are any.
code

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const jsonResultString = '{{ agg_json_result | escapejs }}';
        let aggdataTable;
        let detailedDataTable;
        let editor;
        let dataProcessorWorker;
        console.log('DataTables version:', $.fn.dataTable.version);
        console.log('DataTables Editor version:', $.fn.dataTable.Editor.version);
        editor = new $.fn.dataTable.Editor({
            ajax: function (method, url, data, success, error) {
                if (method === 'PUT') {
                    fetch('{% url "get_aggr_complaints" %}', {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRFToken': '{{ csrf_token }}'
                        },
                        body: JSON.stringify({
                            id: data.data[0].id,
                            data: data.data[0]
                        })
                    })
                    .then(response => response.json())
                    .then(response => {
                        if (response.success) {
                            success(response);
                            showSuccessAlert('Update successful');
                        } else {
                            error(response);
                            showRejectAlert(response.message);
                        }
                    })
                    .catch(error => {
                        console.log('Update failed:', error);
                        showRejectAlert('Error: ' + error.message);
                    });
                }
            },
            table: '#DetailedIncidentsTable',
            fields: [
                { label: "compensation", name: "compensation" }
            ]
        });


        function initializeDetailedDataTable() {
            const element = 'DetailedIncidentsTable';
            const headerText = 'Detailed Complaints Data';
            if (!$.fn.DataTable.isDataTable(`#${element}`)) {
                let detailedTable = $('#DetailedIncidentsTable').DataTable({
                    dom: '<"header">lfrtip',
                    buttons: [],
                    scrollX: true,
                    scrollCollapse: true,
                    fixedColumns: true,
                    fixedColumns: {
                        left: 1
                    },
                    fixedHeader: true,
                    select: {
                        style: 'api',
                        selector: 'td.editable'
                    },
                    order: [[0, "desc"]],
                    autoWidth: true,
                    paging: true,
                    columnDefs: [
                        {className: "text-center", targets: "_all"},
                        {className: "editable  text-center", targets: [10]}
                    ],
                    createdRow: function (row, data, dataIndex) {
                        let flags = data[data.length - 1];
                        if (Array.isArray(flags)) {
                            flags = flags.join(',');
                        }
                        if (flags && flags.includes('no_complaint_date')) {
                            $(row).addClass('highlight-no-complaint-date').removeClass('odd even');
                        }
                        $('td', row).eq(10).attr('data-editor-field', 'compensation');
                        console.log('Set data-editor-field for compensation');
                        console.log('Generated HTML for row:', row.outerHTML);
                    }
                });

                $('#DetailedIncidentsTable').on('click', 'tbody td.editable', function (e) {
                    const field = $(this).attr('data-editor-field');
                    console.log('Clicked editable cell:', this.outerHTML);
                    console.log('Data-editor-field:', field);
                    if (field) {
                        editor.inline(this, {
                            onBlur: 'submit',
                            submit: 'allIfChanged',
                            field: 'compensation'
                        });
                    } else {
                        console.error('No data-editor-field attribute found on clicked cell');
                    }
                });
                $(`#${element}_wrapper .dataTables_length`).append(createResetButton());

                if ($(`#${element}_wrapper .header-inner`).length === 0) {
                    $(`#${element}_wrapper .header`).prepend(`<h2 class="mt-3 text-center table-title">${headerText}</h2>`);
                }
            } else {
                // DataTable already initialized; just ensure buttons and header are correct
                let dt = $('#DetailedIncidentsTable').DataTable();

                if ($(`#${element}_wrapper .header-inner`).length === 0) {
                    $(`#${element}_wrapper .header`).prepend(`<div class='header'><h2 class="mt-3 text-center table-title">${headerText}</h2></div>`);
                }

                // If reset button doesn't exist, create it
                if ($(`#${element}_wrapper .btn-secondary`).length === 0) {
                    $(`#${element}_wrapper .dataTables_length`).append(createResetButton());
                }

            }
        }   
    });

</script>
{% endblock %}

logs.
```get_aggr_complaints:546 Clicked editable cell: <td class=" editable text-center text-
center" data-editor-field="compensation">0</td>
get_aggr_complaints:547 Data-editor-field: compensation
dataTables.editor.min.js:6 Uncaught Unable to automatically determine field from source. Please specify the field name. For more information, please refer to https://datatables.net/tn/11
Yt @ dataTables.editor.min.js:6
H @ dataTables.editor.min.js:6
(anonymous) @ dataTables.editor.min.js:6
each @ datatables.min.js:35
U @ dataTables.editor.min.js:6
individual @ dataTables.editor.min.js:6
he @ dataTables.editor.min.js:6
It @ dataTables.editor.min.js:6
(anonymous) @ get_aggr_complaints:549
dispatch @ jquery-3.7.1.min.js:2
v.handle @ jquery-3.7.1.min.js:2
get_aggr_complaints:546 Clicked editable cell: <td class=" editable text-center text-center" data-editor-field="compensation">0</td>
get_aggr_complaints:547 Data-editor-field: compensation
dataTables.editor.min.js:6 Uncaught Unable to automatically determine field from source. Please specify the field name. For more information, please refer to https://datatables.net/tn/11
Yt @ dataTables.editor.min.js:6
H @ dataTables.editor.min.js:6
(anonymous) @ dataTables.editor.min.js:6
each @ datatables.min.js:35
U @ dataTables.editor.min.js:6
individual @ dataTables.editor.min.js:6
he @ dataTables.editor.min.js:6
It @ dataTables.editor.min.js:6
(anonymous) @ get_aggr_complaints:549
dispatch @ jquery-3.7.1.min.js:2
v.handle @ jquery-3.7.1.min.js:2````

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,270Questions: 26Answers: 4,935
    edited June 18

    Did you follow the troubleshooting steps at the link in the error?
    https://datatables.net/tn/11

    Basically the Editor is not able to map compensation to a Datatables column. Its looking for a columns.data definition with the name compensation. You aren't defining columns.data so one option is to use the Method call technique shown in ht e linked technote. For example:

    editor.inline(this, "compensation", {
    

    However if you are going to inline edit more than on column you might want to define columns.data for the columns matching the -e-option fields.name or maybe you can just use the columns.editField with columnDefs.

    Kevin

  • allanallan Posts: 63,394Questions: 1Answers: 10,450 Site admin
    edited June 18

    The issue is that Editor can't tell what the data point for the cell that inline editing is being triggered on is.

    If you look at the inline editing examples you'll see that the column data point (columns.data) matches the field name (fields.name).

    That is not the case in your table, where there is no columns.data specified, therefore it takes the default which is the column index, 10 in this case. There is no field with that name, thus the error.

    To fix, add editField: 'compensation' to your object in columnDefs for column index 10.

    Note that field: 'compensation' does nothing in the inline() call - there is no field property on the form-options object. You can remove that line.

    Allan

  • allanallan Posts: 63,394Questions: 1Answers: 10,450 Site admin

    Gah - Kevin is faster on the keyboard that me ;-)

    What he said!

  • TurumTurum Posts: 5Questions: 1Answers: 0
    edited June 18

    changed it in this way but now one more error after click
    dataTables.editor.min.js:6 Uncaught Unable to find row identifier For more information, please refer to https://datatables.net/tn/14

    function initializeDetailedDataTable() {
                const element = 'DetailedIncidentsTable';
                const headerText = 'Detailed Complaints Data';
                if (!$.fn.DataTable.isDataTable(`#${element}`)) {
                    let detailedTable = $('#DetailedIncidentsTable').DataTable({
                        dom: '<"header">lfrtip',
                        buttons: [],
                        scrollX: true,
                        scrollCollapse: true,
                        fixedColumns: true,
                        fixedColumns: {
                            left: 1
                        },
                        fixedHeader: true,
                        select: {
                            style: 'api',
                            selector: 'td.editable'
                        },
                        order: [[0, "desc"]],
                        autoWidth: true,
                        paging: true,
                        columnDefs: [
                            {className: "text-center", targets: "_all"},
                            {className: "editable  text-center", targets: [10], editField: 'compensation'}
                        ],
                        createdRow: function (row, data, dataIndex) {
                            let flags = data[data.length - 1];
                            if (Array.isArray(flags)) {
                                flags = flags.join(',');
                            }
                            if (flags && flags.includes('no_complaint_date')) {
                                $(row).addClass('highlight-no-complaint-date').removeClass('odd even');
                            }
                            $('td', row).eq(10).attr('data-editor-field', 'compensation');
                            console.log('Set data-editor-field for compensation');
                            console.log('Generated HTML for row:', row.outerHTML);
                        }
                    });
    
  • kthorngrenkthorngren Posts: 21,270Questions: 26Answers: 4,935

    Did you follow the troubleshooting steps at the link in the error?
    https://datatables.net/manual/tech-notes/14

    Do you have a column with unique identifiers?

    Kevin

  • TurumTurum Posts: 5Questions: 1Answers: 0

    yes I have "key" column in my table, it's unique. and set key as idSrc: 'key' in editor. But got same result, I suppose I'am doing something wrong.


    editor = new $.fn.dataTable.Editor({ ajax: function (method, url, data, success, error) { if (method === 'PUT') { fetch('{% url "get_aggr_complaints" %}', { method: 'PUT', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' }, body: JSON.stringify({ id: data.data[0].id, data: data.data[0] }) }) .then(response => response.json()) .then(response => { if (response.success) { success(response); showSuccessAlert('Update successful'); } else { error(response); showRejectAlert(response.message); } }) .catch(error => { console.log('Update failed:', error); showRejectAlert('Error: ' + error.message); }); } }, table: '#DetailedIncidentsTable', fields: [ { label: "compensation", name: "compensation" } ], idSrc: 'key', });
  • kthorngrenkthorngren Posts: 21,270Questions: 26Answers: 4,935
    edited June 18

    You don't have columns.data defined so your data source is not objects but arrays. See the Data source docs for details. With arrays instead of setting idSrc: 'key', use an integer value that is the 0 based index of the key column. See the idSrc docs for details.

    Kevin

  • TurumTurum Posts: 5Questions: 1Answers: 0

    thanks guys, I fixed this problem and changed my data source from array to object and now I go into edit mode when I click on a cell. But after that, when I press enter, nothing happens. And if I try to fall into another cell, I also cannot do this. Maybe you need an additional handler to send changes to the server.

    document.addEventListener('DOMContentLoaded', function () {
                   editor = new $.fn.dataTable.Editor({
                ajax: function (method, url, data, success, error) {
                    if (method === 'PUT') {
                        fetch('{% url "get_aggr_complaints" %}', {
                            method: 'PUT',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRFToken': '{{ csrf_token }}'
                            },
                            body: JSON.stringify({
                                id: data.data[0].key,
                                data: data.data[0]
                            })
                        })
                            .then(response => response.json())
                            .then(response => {
                                if (response.success) {
                                    success(response);
                                    showSuccessAlert('Update successful');
                                } else {
                                    error(response);
                                    showRejectAlert(response.message);
                                }
                            })
                            .catch(error => {
                                console.log('Update failed:', error);
                                showRejectAlert('Error: ' + error.message);
                            });
                    }
                },
                table: '#DetailedIncidentsTable',
                fields: [
                    {label: "compensation", name: "compensation"}
                ],
                idSrc: 'key',
            });
     function initializeDetailedDataTable(data) {
                const element = 'DetailedIncidentsTable';
                const headerText = 'Detailed Complaints Data';
                if (!$.fn.DataTable.isDataTable(`#${element}`)) {
                    let detailedTable = $('#DetailedIncidentsTable').DataTable({
                        dom: '<"header">lfrtip',
                        buttons: [],
                        scrollX: true,
                        scrollCollapse: true,
                        fixedColumns: true,
                        fixedColumns: {
                            left: 1
                        },
                        fixedHeader: true,
                        select: {
                            style: 'api',
                            selector: 'td.editable'
                        },
                        order: [[0, "desc"]],
                        autoWidth: true,
                        paging: true,
                        data: data,
                        columns: [
                            {data: "key", title: "Key", className: "text-center"},
                            {data: "status", title: "Status", className: "text-center"},
                            {data: "resolution", title: "Resolution", className: "text-center"},
                            {data: "create_datetime", title: "Create Date", className: "text-center"},
                            {data: "resolved_datetime", title: "Resolved Date", className: "text-center"},
                            {data: "complaint_date", title: "Complaint Date", className: "text-center"},
                            {data: "complaint_type", title: "Complaint Type", className: "text-center"},
                            {data: "sf_case_number", title: "SF Case Number", className: "text-center"},
                            {data: "uid", title: "UID", className: "text-center"},
                            {data: "mt_servers", title: "MT Servers", className: "text-center"},
                            {
                                data: "compensation",
                                title: "Compensation",
                                className: "editable text-center",
                                editField: 'compensation'
                            },
                            {data: "complaint_event", title: "Complaint Event", className: "text-center"},
                            {data: "event_type", title: "Event Type", className: "text-center"},
                            {data: "labels", title: "Labels", className: "text-center"},
                            {data: "accounts", title: "Accounts", className: "text-center"},
                            {data: "account_types", title: "Account Types", className: "text-center"},
                            {data: "orders", title: "Orders", className: "text-center"},
                            {data: "is_any_abuser", title: "Is Any Abuser", className: "text-center"},
                            {data: "client_value", title: "Client Value", className: "text-center"},
                            {data: "client_country", title: "Client Country", className: "text-center"},
                            {data: "incidents", title: "Incidents", className: "text-center"},
                            {data: "is_correct", title: "Is Correct", className: "text-center"}
                        ],
                        columnDefs: [
                            {className: "text-center", targets: "_all"},
                        ],
                        createdRow: function (row, data, dataIndex) {
                            let flags = data[data.length - 1];
                            if (Array.isArray(flags)) {
                                flags = flags.join(',');
                            }
                            if (flags && flags.includes('no_complaint_date')) {
                                $(row).addClass('highlight-no-complaint-date').removeClass('odd even');
                            }
                            $('td', row).eq(10).attr('data-editor-field', 'compensation');
                            console.log('Set data-editor-field for compensation');
                            console.log('Generated HTML for row:', row.outerHTML);
                        }
                    });
    
                    $('#DetailedIncidentsTable').on('click', 'tbody td.editable', function (e) {
                        const field = $(this).attr('data-editor-field');
                        console.log('Clicked editable cell:', this.outerHTML);
                        console.log('Data-editor-field:', field);
                        if (field) {
                            console.log('Initializing inline edit for field:', field);
                            editor.inline(this);
                        } else {
                            console.error('No data-editor-field attribute found on clicked cell');
                        }
                    });
                    $(`#${element}_wrapper .dataTables_length`).append(createResetButton());
    
                    if ($(`#${element}_wrapper .header-inner`).length === 0) {
                        $(`#${element}_wrapper .header`).prepend(`<h2 class="mt-3 text-center table-title">${headerText}</h2>`);
                    }
                } else {
                    // DataTable already initialized; just ensure buttons and header are correct
                    let dt = $('#DetailedIncidentsTable').DataTable();
    
                    if ($(`#${element}_wrapper .header-inner`).length === 0) {
                        $(`#${element}_wrapper .header`).prepend(`<div class='header'><h2 class="mt-3 text-center table-title">${headerText}</h2></div>`);
                    }
    
                    // If reset button doesn't exist, create it
                    if ($(`#${element}_wrapper .btn-secondary`).length === 0) {
                        $(`#${element}_wrapper .dataTables_length`).append(createResetButton());
                    }
    
                }
            }
             function transformDetailedData(data) {
                return data.map(item => {
                    const link = document.createElement('a');
                    link.href = item.link;
                    link.textContent = item.key;
                    link.target = "_blank";
                    const linkCell = document.createElement('td');
                    linkCell.appendChild(link);
    
                    return {
                        key: linkCell.outerHTML,
                        status: item.status,
                        resolution: item.resolution,
                        create_datetime: item.create_datetime,
                        resolved_datetime: item.resolved_datetime,
                        complaint_date: item.complaint_date,
                        complaint_type: item.complaint_type,
                        sf_case_number: item.sf_case_number,
                        uid: item.uid ? processUid(item.uid) : '',
                        mt_servers: item.mt_servers ? processMtServersMmo(item.mt_servers) : '',
                        compensation: item.compensation,
                        complaint_event: item.complaint_event,
                        event_type: item.event_type ? processItems(item.event_type) : '',
                        labels: item.labels ? processItems(item.labels) : '',
                        accounts: item.accounts ? processItems(item.accounts) : '',
                        account_types: item.account_types ? processItems(item.account_types) : '',
                        orders: item.orders ? processItems(item.orders) : '',
                        is_any_abuser: item.is_any_abuser,
                        client_value: item.client_value,
                        client_country: item.client_country,
                        incidents: item.incidents ? formatIncidentsLinks(item.incidents) : '',
                        is_correct: item.is_correct
                    };
                });
            }
    let transformedData = transformDetailedData(responseData.result.result_details);
    initializeDetailedDataTable(transformedData);
    
        });
    
  • kthorngrenkthorngren Posts: 21,270Questions: 26Answers: 4,935
    edited June 19 Answer ✓

    I believe this is the code you have for inline editing:

                    $('#DetailedIncidentsTable').on('click', 'tbody td.editable', function (e) {
                        const field = $(this).attr('data-editor-field');
                        console.log('Clicked editable cell:', this.outerHTML);
                        console.log('Data-editor-field:', field);
                        if (field) {
                            console.log('Initializing inline edit for field:', field);
                            editor.inline(this);
                        } else {
                            console.error('No data-editor-field attribute found on clicked cell');
                        }
                    });
    

    Looks like this should work. Have you checked the browser's console for errors?

    Possibly there is n issue with your Editor's ajax function. I'm not sure just by looking at the code.

    Kevin

  • TurumTurum Posts: 5Questions: 1Answers: 0

    Ahh, this is in ajax:, the editor does not send the method to the function and the check for PUT was unnecessary there. Thanks guys, you are the best.

Sign In or Register to comment.