I'm using datatables and yadcf to filter on month and weekday, but cannot get the sorting right for the select lists.
<table id="myTable" class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Month</th>
<th>Weekday</th>
</tr>
</thead>
</table>
var myData = [
{"Id":1,"Name":"Test 1","Month":{"Id":5,"Label":"May"},"Weekday":{"Id":3,"Label":"Tuesday"}},
{"Id":2,"Name":"Test 2","Month":{"Id":5,"Label":"May"},"Weekday":{"Id":3,"Label":"Tuesday"}}
...
];
$(function () {
var Table = $('#myTable').DataTable({
'data': myData,
"columns" : [
{ "targets": 0, "data" : "Id" },
{ "targets": 1, "data" : "Name" },
{ "targets": 2, "data": function ( data, type, val, meta ) {
if (type === 'display') {
return data.Month.Label;
}else if (type === 'filter') {
return data.Month.Label;
}
// 'sort', 'type' and undefined all just use the integer
return data.Month.Id;
} },
{ "targets": 3, "data": function ( data, type, val, meta ) {
if (type === 'display') {
return data.Weekday.Label;
}else if (type === 'filter') {
return data.Weekday.Label;
}
// 'sort', 'type' and undefined all just use the integer
return data.Weekday.Id;
} }
]
});
yadcf.init(Table, [
{
column_number : 2,
filter_type: 'select',
filter_match_mode: 'exact',
style_class: 'form-control'
},
{
column_number : 3,
filter_type: 'select',
filter_match_mode: 'exact',
style_class: 'form-control'
}
]);
} );
How do I order these filters so they order January, February, March and the weekdays Monday, Tuesday, Wednesday etc.?
Fiddle: https://jsfiddle.net/Webkungen/jLq6okgc/2/
If I add a custom sort function for the filter and return data.Month.Id for the filter the sorting will be right but then the month number is shown in the filter instead of it's name.
Appreciate any help on this as it's driving me crazy, thanks!
You should use the sort_as: 'custom',
sort_as_custom_func: monthSort
And implement your own sorting function, here is a quick way:
$(function () {
var Table = $('#myTable').DataTable({
'data': myData,
"columns" : [
{ "data" : "Id" },
{ "data" : "Name" },
{ "data" : "Month.Label" },
{ "data" : "Weekday.Label" }
]
});
yadcf.init(Table, [
{
column_number : 2,
filter_type: 'select',
filter_match_mode: 'exact',
style_class: 'form-control',
sort_as: 'custom',
sort_as_custom_func: monthSort
},
{
column_number : 3,
filter_type: 'select',
filter_match_mode: 'exact',
style_class: 'form-control'
}
]);
function monthSort(a, b){
var months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
return months.indexOf(a) - months.indexOf(b);}
} );