Thursday, March 21, 2019

Laravel Row reorder implementation

I was able to get this working in Laravel using Yajra Datatables as a Service.Here is the example below, 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 :
/**
 * 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 );
    }
}

 Thanks for partially share by the exninja

1 comment: