Laravel-datatables: Row reorder implementation

Created on 19 Oct 2015  ·  7Comments  ·  Source: yajra/laravel-datatables

I can't get rowReorder fixed on my DataTable. Currently my code looks like this:

Inside my view file:

<table class="table table-bordered table-striped" id="pages-table" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th class="col-md-1">Sequence</th>
            <th class="col-md-8">Title</th>
            <th class="col-md-1"></th>
             <th class="col-md-1"></th>
             <th class="col-md-1"></th>
         </tr>
    </thead>
</table>

JavaScript:

$(function() {
    $('#pages-table').DataTable({
        stateSave: true,
        processing: true,
        serverSide: true,
        rowReorder: true,
        ajax: {
            url: '{!! url('admin/test/data') !!}',
            type: 'POST',
            data: { _token: '{!! csrf_token() !!}' }
        },
        columns: [
            {data: 'sequence', name: 'sequence'},
            {data: 'title', name: 'title'},
            {data: 'active', name: 'active', orderable: false, searchable: false},
            {data: 'edit', name: 'edit', orderable: false, searchable: false},
            {data: 'delete', name: 'delete', orderable: false, searchable: false}
        ]
    });
});

The table is rendered perfectly with the data inside. But my question is: How can I set the rowreordering index to use the sequence. Because now it uses an index that just starts at 0 on the first row.

Most helpful comment

@sujeetjaiswara
Thanks partly to the solution from @alexgiuvara I was also able to get this working in Laravel using Yajra Datatables as a Service. My coding might not be optimized yet as I only just implemented this, but hopefully you get the idea.

In my DataTable Builder:

return $this->builder()
    ->columns([
        'id' => [ 'visible' => false ], // record id
        'sortsequence' => [ ... ],  // db column containing order sequence
        ...,
    ])
    ->parameters([
        ...
        'rowReorder' => [
            'selector' => 'tr>td:not(:last-child)', // I allow all columns for dragdrop except the last
            'dataSrc' => 'sortsequence',
            'update' => false // this is key to prevent DT auto update
        ]
    ]);

Blade:

// includes DataTables JS/CSS plus the folliowing:
...
<meta name="csrf-token" content="{{ csrf_token() }}”>
...
<link rel="stylesheet" href="https://cdn.datatables.net/rowreorder/1.2.0/css/rowReorder.dataTables.min.css”>
...
<script src="https://cdn.datatables.net/rowreorder/1.2.0/js/dataTables.rowReorder.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){  
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    var table = $('#dataTableBuilder').DataTable();
    table.on( 'row-reorder', function ( e, diff, edit ) {
        var myArray = [];
        for ( var i=0, ien=diff.length ; i<ien ; i++ ) {
            var rowData = table.row( diff[i].node ).data();
        myArray.push({
            id: rowData.id,         // record id from datatable
            position: diff[i].newData       // new position
        });
        }
       var jsonString = JSON.stringify(myArray);
       $.ajax({
                url     : '{{ URL::to('myurl/reorder') }}',
                type    : 'POST',
                data    : jsonString,
                dataType: 'json',
                success : function ( json ) 
                {
                $('#dataTableBuilder').DataTable().ajax.reload(); // now refresh datatable
                    $.each(json, function (key, msg) {
                    // handle json response
                    });
                }
            });
    });

});
</script>

Route:
Route::post('myurl/reorder', 'MyController@reorder')->name('myname.reorder');

MyController (redacted):

/**
 * Reorder a listing of the resource.
 *
 * @return Response
 */
public function reorder(Request $request)
{
    $count = 0;

    if (count($request->json()->all())) {
        $ids = $request->json()->all();
        foreach($ids as $i => $key)
        {
            $id = $key['id'];
            $position = $key['position'];
            $mymodel = MyModel::find($id);
            $mymodel->sortsequence = $position;
            if($mymodel->save())
            {
                $count++;
            }
        }
        $response = 'send response records updated goes here';
        return response()->json( $response );
    } else {
        $response = 'send nothing to sort response goes here';
        return response()->json( $response );
    }
}

All 7 comments

@gjportegies, Unfortunately, I think rowReorder is not compatible with server-side implementation of datatables. I just tried it and the re-order works. However, when you drag the row, it will trigger a redraw which will fetch and reload the data from the server. Datatables does not send any details that pertains to the re-ordered row which makes it impossible to retain or write an ordering query as specified.

Would be nice to be able to have the option to set the column to reorder.

Hi

I just solved this problem. Please check out my answer here: http://stackoverflow.com/questions/27309655/datatables-rowreordering-after-serverside-processiong-completed/37887034#37887034

Now you can reorder DataTables rows with serverSide processing and without table reloading

Best wishes,
Alex

@alexgiuvara good to hear that you were able to solve this. And I think I am going to have this kind of requirement on my project and will definitely try your solution. Thanks for sharing!

hi, Anyone have data-table js row-reordering solution for laravel. its urgent please mail [email protected]

@sujeetjaiswara
Thanks partly to the solution from @alexgiuvara I was also able to get this working in Laravel using Yajra Datatables as a Service. My coding might not be optimized yet as I only just implemented this, but hopefully you get the idea.

In my DataTable Builder:

return $this->builder()
    ->columns([
        'id' => [ 'visible' => false ], // record id
        'sortsequence' => [ ... ],  // db column containing order sequence
        ...,
    ])
    ->parameters([
        ...
        'rowReorder' => [
            'selector' => 'tr>td:not(:last-child)', // I allow all columns for dragdrop except the last
            'dataSrc' => 'sortsequence',
            'update' => false // this is key to prevent DT auto update
        ]
    ]);

Blade:

// includes DataTables JS/CSS plus the folliowing:
...
<meta name="csrf-token" content="{{ csrf_token() }}”>
...
<link rel="stylesheet" href="https://cdn.datatables.net/rowreorder/1.2.0/css/rowReorder.dataTables.min.css”>
...
<script src="https://cdn.datatables.net/rowreorder/1.2.0/js/dataTables.rowReorder.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){  
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    var table = $('#dataTableBuilder').DataTable();
    table.on( 'row-reorder', function ( e, diff, edit ) {
        var myArray = [];
        for ( var i=0, ien=diff.length ; i<ien ; i++ ) {
            var rowData = table.row( diff[i].node ).data();
        myArray.push({
            id: rowData.id,         // record id from datatable
            position: diff[i].newData       // new position
        });
        }
       var jsonString = JSON.stringify(myArray);
       $.ajax({
                url     : '{{ URL::to('myurl/reorder') }}',
                type    : 'POST',
                data    : jsonString,
                dataType: 'json',
                success : function ( json ) 
                {
                $('#dataTableBuilder').DataTable().ajax.reload(); // now refresh datatable
                    $.each(json, function (key, msg) {
                    // handle json response
                    });
                }
            });
    });

});
</script>

Route:
Route::post('myurl/reorder', 'MyController@reorder')->name('myname.reorder');

MyController (redacted):

/**
 * Reorder a listing of the resource.
 *
 * @return Response
 */
public function reorder(Request $request)
{
    $count = 0;

    if (count($request->json()->all())) {
        $ids = $request->json()->all();
        foreach($ids as $i => $key)
        {
            $id = $key['id'];
            $position = $key['position'];
            $mymodel = MyModel::find($id);
            $mymodel->sortsequence = $position;
            if($mymodel->save())
            {
                $count++;
            }
        }
        $response = 'send response records updated goes here';
        return response()->json( $response );
    } else {
        $response = 'send nothing to sort response goes here';
        return response()->json( $response );
    }
}

Many thanks

On 06-Mar-2017 2:17 AM, "exninja" notifications@github.com wrote:
>

@sujeetjaiswara
Thanks partly to the solution from @alexgiuvara I was also able to get
this working in Laravel using Yajra Datatables as a Service. My coding
might not be optimized yet as I only just implemented this, but hopefully
you get the idea.

In my DataTable Builder:

return $this->builder()
->columns([
'id' => [ 'visible' => false ], // record id
'sortsequence' => [ ... ], // db column containing order sequence
...,
])
->parameters([
...
'rowReorder' => [
'selector' => 'tr>td:not(:last-child)', // I allow all
columns for dragdrop except the last
'dataSrc' => 'sortsequence',
'update' => false // this is key to prevent DT auto update
]
]);

Blade:

// includes DataTables JS/CSS plus the folliowing:
...

Route:
Route::post('myurl/reorder', 'MyController@reorder
')->name('myname.reorder');

MyController (redacted):

/**

  • Reorder a listing of the resource.
    *
  • @return Response
    */
    public function reorder(Request $request)
    {
    $count = 0;
if (count($request->json()->all())) {
    $ids = $request->json()->all();
    foreach($ids as $i => $key)
    {
        $id = $key['id'];
        $position = $key['position'];
        $mymodel = MyModel::find($id);
        $mymodel->sortsequence = $position;
        if($mymodel->save())
        {
            $count++;
        }
    $response = 'send response records updated';
    return response()->json( $response );
    }

} else {
    $response = 'send nothing to sort response';
    return response()->json( $response );
}

}


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub, or mute the thread.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

josiahke picture josiahke  ·  3Comments

alejandri picture alejandri  ·  3Comments

jgatringer picture jgatringer  ·  3Comments

t0n1zz picture t0n1zz  ·  3Comments

FilipeBorges1993 picture FilipeBorges1993  ·  3Comments