问题
Laravel: 5.6.39
PHP: 7.2.10
Yajra Table: 8.0
Sample code
$(document).ready( function() {
var url = "{{ url('/admin/videos') }}";
$(function() {
var oTable = $('#admin-videos').DataTable({
dom: "<'row'<'col-xs-12'<'col-xs-6'l><'col-xs-6'p>>r>"+
"<'row'<'col-xs-12't>>"+
"<'row'<'col-xs-12'<'col-xs-6'i><'col-xs-6'p>>>",
processing: true,
serverSide: true,
ajax: {
url: url,
data: function (d) {
d.category = $("#category option:selected").val();
d.language = $("#language option:selected").val();
}
},
columns: [
{ data: 'video_checkbox', name: 'video_checkbox' },
{ data: 'created_at', name: 'created_at' },
{ data: 'video_label', name: 'video_label' },
{ data: 'video_link', name: 'video_link' },
{ data: 'view', name: 'view' },
{ data: 'video_category', name: 'video_category' },
],
stateSave: true,
bDestroy: true,
});
$('#search-form').on('submit', function(e) {
oTable.draw();
e.preventDefault();
});
});
});
Now if I will remove dom
search and filter both can be seen but search will still not work, if I will remove the filters then only search is working, I believe there should be some customization to dom or something, that will allow both search and filters.
In documentation too, there is no search.
There is one option to enable search like below code, but it does not seems to be working, also for that I have removed dom attribute in above code.
search: {
"regex": true
}
回答1:
I do not know how the search works automatically, but I have coded for my requirement and that is working fine and give some idea, how you can do it.
You can get search term using $request->get('search')['value']
and now write code to check if your condition is getting satisfied and filter the results in your controller or Model. Below is the code to do it in Controller.
return DataTables::eloquent($videos)
->filter(function ($query) use ($request) {
if ($request->has('category') && ! is_null($request->get('category'))) {
$query->where('video_category', $request->get('category'));
}
if ($request->has('language') && ! is_null($request->get('language')) ) {
$query->where('video_language', $request->get('language'));
}
if ($request->has('search') && ! is_null($request->get('search')['value']) ) {
$regex = $request->get('search')['value'];
return $query->where('your_field', 'like', '%' . $regex . '%');
});
}
})->toJson();
来源:https://stackoverflow.com/questions/54978555/yajra-data-table-using-search-and-custom-filter-together