row.add() not respecting colReorder

row.add() not respecting colReorder

dkercherdkercher Posts: 11Questions: 3Answers: 0
edited February 26 in Free community support

Test case: https://live.datatables.net/diqesedo/1/edit

I might be missing something simple, but if I add a new row with row.add(), how do I make it respect colReorder. In the sample case I use an array meant to simulate the original order. I would want the data to be added in reverse. In my real app I use a string <tr> element from my server side template (rails). I have these <tr> strings in json (rowData) and call the following:

table.clear().draw();
rowData.forEach(function (trString) {
table.row.add($(trString)).draw();
});

Do I need to get the order from my DataTable and manually switch around the data or is there a way to tell tell DataTables that what I'm adding is being send in the original column order and needs to be moved around since the order has changed?

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,681Questions: 1Answers: 10,498 Site admin

    I would 100% recommend using object based data with ColReorder. It saves the headaches.

    ColReorder 1.x would actually reorder the data source arrays. ColReorder 2.x does not do that any more.

    Allan

  • kthorngrenkthorngren Posts: 21,443Questions: 26Answers: 4,974
    Answer ✓

    Looks like I was working on this at the same time Allan was posting :smile:

    ColReorder 1.x would actually reorder the data source arrays.

    The test case has ColReorder 1.6.2 and it doesn't seem to reorder the array data. Datatables stores the array based data in an object based structure so array index 0 looks like {0: 'myData'}. You could take advantage of that and use colReorder.order() to get the current order and iterate the aray to build an object based on the colReorder.order(). For example:
    https://live.datatables.net/diqesedo/2/edit

    However as Allan suggested using objects are much easier. You can use columns.data for this but it will require changing other code you may have that uses arrays. For example:
    https://live.datatables.net/diqesedo/3/edit

    Kevin

  • dkercherdkercher Posts: 11Questions: 3Answers: 0
    edited February 27

    Thanks! I ended up going with the approach of looping through and reordering based on colReorder.order() I like the idea of columns.data, but it gets complicated when you have a lot of server side templating. Really it's just a choice of looping on the front-end or back-end, but on the front-end I can check if the order is sequential and skip it.

    I might look into a restructure that allows for column data in the future though, cheers!

Sign In or Register to comment.