Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mtigdemir/9e1e2f2821601d1372e7ef274d695dbb to your computer and use it in GitHub Desktop.
Save mtigdemir/9e1e2f2821601d1372e7ef274d695dbb to your computer and use it in GitHub Desktop.
Populate external drop downs for datatable filtering
<!-- Holder div for filter select boxes -->
<div id="table_filters" class="form-row"></div>
<table class='table datatable' id="registrations">
<thead class='thead-light'>
<tr>
<th>Product</th>
<th>Type</th>
<th>Status</th>
<th>Registration Date</th>
<th>Renewal Date</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function() {
$("#registrations").dataTable( {
"ajax": '{!! route('ajax.registrations') !!}',
processing: true,
serverSide: true,
columns: [
{data: "product.name"},
{data: "reg_type.type"},
{data: "status"},
{data: "reg_date"},
{data: "renew_date"},
],
initComplete: function (settings, json) {
this.api().columns([0,2,3]).every( function () {
var column = this;
// Use column title as label for select
var title = $(column.header()).text();
// Generate Label
var label = $('<div class="col-md-3"><label>'+title+'</label></div>').appendTo($("#table_filters"));
// Generate select
var select = $('<select class="form-control"><option value="">Show All</option></select>')
.appendTo( label )
// Search when selection is changed
.on( 'change', function () {
var val = $(this).val();
column.search( this.value ).draw();
} );
// Capture the data from the JSON to populate the select boxes with all the options
var extraData = (function(i) {
switch(i) {
case 0:
return json.allProducts;
case 2:
return json.allTypes;
case 3:
return json.allStatus;
}
})(column.index());
// Draw select options
extraData.forEach( function ( d ) {
if(column.search() === d){
select.append( '<option value="'+d+'" selected="selected">'+d+'</option>' )
} else {
select.append( '<option value="'+d+'">'+d+'</option>' )
}
} );
} );
}
});
});
</script>
/**
* Process datatables ajax request.
*
* @return \Illuminate\Http\JsonResponse
*/
public function allData(Request $request)
{
$registrations = Registration::with('product')->with('reg_type')->select('registrations.*');
$datatable = Datatables::of($registrations);
if($request->draw == 1) {
$products = \App\Product::active()->distinct('name')->pluck('name');
$types = \App\RegType::active()->distinct('type')->pluck('type');
$status = Registration::distinct('status')->pluck('status');
$datatable->with([
'allProducts' => $products,
'allTypes' => $types,
'allStatus' => $status,
]);
}
return $datatable->make(true);
}
Route::group(['prefix' => 'ajax'], function() {
Route::get('registrations', 'RegistrationController@allData')->name('ajax.registrations');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment