Programmatically moving a row with RowReorder

Programmatically moving a row with RowReorder

jbobsonjbobson Posts: 1Questions: 1Answers: 0

Hello,

I posted this on StackOverflow, but didn't receive a response. I hope I can get some help here (jsfiddle:
https://jsfiddle.net/84L2kf24/4/ ):

I have the following requirements with a DataTable table:

Allow the user to move rows around manually.
Allow the user to press a button to move a row to the top/bottom of the table.
The first requirement is easy to satisfy with the RowReorder plug-in.

I wrote the following code to handle the second requirement:

 $table.find('tbody').on('click', '.move-to-top-btn', function() {
     var $row = $(this).closest('tr'),
         index = $row.index();
 
     if (index === 0) {
         return;
     }
 
     var rowToMoveUp = dt.row(index).data();
 
     // Move through each row, bump the previous row up one:
     for (var i = index; i > 0; --i) {
         var rowData = dt.row(i - 1).data();
         rowData[0]++;
 
         dt.row(i).data(rowData);
     }
 
     rowToMoveUp[0] = 0;
     dt.row(0).data(rowToMoveUp);
 
     dt.draw(true);
 });

Basically, I manually move the data of each row around, and update the first column, which is the ID that the table is sorted on. Once I call draw(), the table updates in the way I expect.

Both of these work independent of each other. However, if the user uses the mouse to reposition a row manually, then uses the button to move the row to the top, it behaves incorrectly.

What is the correct way to programmatically move rows around the table in this situation?

To see a full demonstration of the effect, see this jsfiddle:

https://jsfiddle.net/84L2kf24/4/

Answers

  • allanallan Posts: 64,106Questions: 1Answers: 10,574 Site admin

    Sorry - there is no way to programmatically reorder rows with RowReorder at the moment. This actually came up in a github issue a week or so ago.

    Your best bet is to implement your own reorder using the API as you have done. I think the problem with it is that you are just moving the whole data row object around, rather than an individual value like RowReorder does (rowReorder.dataSrc).

    Allan

This discussion has been closed.