Change page after editing...

Change page after editing...

marianidiegomarianidiego Posts: 69Questions: 21Answers: 1

I have been using Datatables for a few years now. And I'm always learning! But there is one thing I have never found a real solution for.

Let's say we have a long table, several pages long. So the "paging:true".

I scroll through the pages, and find a value to moficate on page 3. I select the row, edit the value, when the edit finishes the table does a reload, reloads the whole table for me, and goes back to page 1. But why can't it stay on page 3 !?!! I waste a lot of time changing pages every time.

To improve the situation, I take control of the editor and at Submit, I run a fatherTable.page(currentPage).draw(false); instead of its reload. That works. But isn't there a more elegant solution?

Below I share with you my "standard" code for a table, maybe you have some useful tips I can apply...

Code:
fatherEditor = new $.fn.dataTable.Editor( {
"language": {"url": "https://cdn.datatables.net/plug-ins/2.1.8/i18n/it-IT.json"},
"serverSide": true,
ajax: {
url: 'dist/cont/tpl_commission/calc_commission.php',
type: 'POST',
data: function ( d ) {
d.csrf_token = "AF7E60CAD5BB3E3399C21559AA930B60378C671EF1AEF610F7E4CC293F891120";
}
},
"table": "#commission",
"fields": [
{
label: "Contenzioso:",
name: "login_commission_contentions.contentions",
type: 'textarea',
attr: { disabled: true }
},
{
label: "Risposta",
name: "login_commission_contentions.reply_contentions",
type: 'textarea',
},
...

                    ]
                });


                // Variabile per memorizzare la pagina corrente
                let currentPage = 0;

                // Evento chiamato prima della sottomissione del form dell'Editor
                fatherEditor.on('preSubmit', function(e, data, action) {
                    // Salva la pagina corrente della tabella prima di inviare i dati
                    currentPage = fatherTable.page();
                });

                // Evento chiamato quando la sottomissione ha successo
                fatherEditor.on('submitSuccess', function(e, json, data, action) {

                    //fatherTable.ajax.reload(function() {
                        try {
                            // Ripristina la paginazione alla pagina salvata
                            fatherTable.page(currentPage).draw(false); // 'draw(false)' per non resettare la paginazione
                            //fatherTable.ajax.reload(null,false);
                        } catch (error) {
                            console.warn("Rirpostino della pagina non riuscito:", error);
                        }
                        // Resetta currentPage dopo l'uso per evitare effetti indesiderati in operazioni future
                        currentPage = 0;
                    //});
                });

                fatherTable = $('#commission').DataTable({
                    "language": {"url": "https://cdn.datatables.net/plug-ins/2.1.8/i18n/it-IT.json"},
                    "serverSide": false,
                    ajax: {
                        url: 'dist/cont/tpl_commission/calc_commission.php',
                        type: 'POST',
                        data: function ( d ) {
                                d.csrf_token = "AF7E60CAD5BBEF610F7E4CC293F891120";
                        }
                    },
                    paging:                         true,
                    stateSave:                      false,
                    searchBuilder: {
                        preDefined: {
                            criteria: [
                                .....
                            ],
                            logic: 'AND'
                        }
                    },
                    columns: [
                        {   // 0
                            class:                  "dtr-control",
                            width:                  '5px',
                            data:                   null,
                            defaultContent:         "",
                            orderable:              false,
                            responsivePriority:     1
                        },
                        {   // 1
                            title:                  "Venditore",            
                            data:                   "login.email",
                            render:                 function ( data, type, row ) {
                                                        return  data;
                                                        return '('+ row.clients.represented + ') ' + data;
                                                    }                   
                        },
                        ....
                        {
                            data:                   null,
                            defaultContent:         '<i class="fa fa-pencil text-info"/>',
                            className:              'row-edit dt-center',
                            orderable:              false,
                            width:                  '10px',
                            responsivePriority:     1,
                                                }

                    ],
                    columnDefs: [
                        ....
                    ],
                    buttons: [      
                        ....
                    ],

                    order: [[3, 'asc'], [2, 'asc']],

                });

                // Edit record
                fatherTable.on('click', 'td.row-edit', function (e) {
                    fatherEditor.edit(e.target.closest('tr'), {
                        title: 'Modifica',
                        buttons: 'Salva'
                    });
                });

                // Delete a record
                fatherTable.on('click', 'td.row-remove', function (e) {
                    fatherEditor.remove(e.target.closest('tr'), {
                        title: 'Cancellare la riga',
                        message: 'È sicuro di voler rimuovere questa registrazione?',
                        buttons: 'Cancella'
                    });
                });

                // On right mouse press -> Edit
                fatherTable.on('contextmenu', 'tbody tr', function (e) {
                    e.preventDefault();
                    e = e || window.event;
                    var isRightMB;

                    if ("which" in e)               // Gecko (Firefox), WebKit (Safari/Chrome) & Opera
                        isRightMB = e.which == 3; 
                    else if ("button" in e)         // IE, Opera 
                        isRightMB = e.button == 2; 

                    if(isRightMB)
                        fatherEditor.edit( this, {
                            title: 'Modifica',
                            buttons: 'Salva'
                        });
                });

                $(window).on('resize', function () {
                    try {   // A volte la tabella non è ancora fomata
                        fatherTable.columns.adjust();
                    } catch (error) {}
                });

Description of problem:
I would like to write the whole thing more systematically. Calls like:

$(window).on('resize', function () { fatherTable.columns.adjust();
fatherTable.on('click', ....
fatherTable.on('contextmenu' ...
fatherEditor.on('submitSuccess',...
fatherEditor.on('preSubmit', ...

repeat on each page, and if there are multiple tables per page, I have to write them each time. Hasn't a more elegant form of doing this been arranged?

Answers

  • allanallan Posts: 64,519Questions: 1Answers: 10,664 Site admin

    I scroll through the pages, and find a value to moficate on page 3. I select the row, edit the value, when the edit finishes the table does a reload, reloads the whole table for me, and goes back to page 1

    It shouldn't - it should stay on page 3. That is what happens in this example.

    Can you link to a test case showing the issue for me please?

    Allan

  • kthorngrenkthorngren Posts: 22,015Questions: 26Answers: 5,081
    edited June 4

    I assume you are referring to this code?

            try {
                // Ripristina la paginazione alla pagina salvata
                fatherTable.page(currentPage).draw(false); // 'draw(false)' per non resettare la paginazione
                //fatherTable.ajax.reload(null,false);
            } catch (error) {
                console.warn("Rirpostino della pagina non riuscito:", error);
            }
    

    fatherTable.page(currentPage).draw(false);

    This is expected to stay on the page that currentPage references. Use the browser's debugger or console log statement to verify the value of currentPage. Not sure what this does for you in submitSuccess as it doesn't read the page's data from the server since you have "serverSide": false,.

    //fatherTable.ajax.reload(null,false);

    Doing this is also expected to stay on the same page assuming it's uncommented :smile: This will reload the full data set from the server since you have "serverSide": false,.

    Do you actually need the code in submitSuccess? Maybe try editing without using submitSuccess, does it work correctly? Typically, as hte example Allan posted shows, the data will be updated properly. This assumes the proper response from the server. See the Editor client server data docs for details.

    For help debugging please post the test case Allan asked for.

    Kevin

  • kthorngrenkthorngren Posts: 22,015Questions: 26Answers: 5,081
    edited June 4

    Hasn't a more elegant form of doing this been arranged?

    For the Datatables you might be able to use a jquery selector like $("table") to select the table elements. See this example, make sure to select the jQuery view at the top of the page.

    Do you execute the same code for each Datatable event?

    For Editor the only reference is a Javascript variable. I'm not familiar with an Editor feature that would aggregate these to allow for creating one event handler. Again are you doing the same thing in each preSubmit, for example, for each Editor instance?

    Kevin

  • marianidiegomarianidiego Posts: 69Questions: 21Answers: 1

    Since Allan's example worked, I need to succeed too.... :#

    Il mio esempio "live" si trova qui: https://admin.cleanlife.ch/commissiontest.php

    I'll try to update the datatable libraries, I don't want it to be one of those....

  • kthorngrenkthorngren Posts: 22,015Questions: 26Answers: 5,081

    Were you posting a link to a test case? All I see is this page:

    Please provide the correct URL or the steps needed to see the test case.

    Kevin

  • marianidiegomarianidiego Posts: 69Questions: 21Answers: 1

    Correct. It works now. You can edit the data too.

  • marianidiegomarianidiego Posts: 69Questions: 21Answers: 1

    Have you found where the problem might be?

  • allanallan Posts: 64,519Questions: 1Answers: 10,664 Site admin

    I've just been looking into it and it is due to the filter applied to the table by SearchBuilder. If you remove the search terms and then perform the edit, the page doesn't reset back to 0. Tracing that through lead me to a bug in SearchBuilder which was causing it to redraw an extra time after an edit.

    I've committed a fix. That will be in the nightly shortly, and it will be in the next SearchBuilder release.

    Thanks for your help with reporting this and providing a test case for it.

    Allan

Sign In or Register to comment.