1

I am using jquery Datatables with moment.js and yadcf-plugin.

In my table I have a datefield in the format dd.mm.yyyy - to sort it correctly I use the moment-plugin, this works great.

But in the yadcf-filter, it is sorted as "alpha", like

  • 01.09.2020
  • 21.05.2019
  • 30.04.2020
  • 30.08.2025
  • 31.12.2017
  • 31.12.2021

but I need

  • 31.12.2017
  • 21.05.2019
  • 30.04.2020
  • 01.09.2020
  • 31.12.2021
  • 30.08.2025

How can I sort the values with moment.js?

Thank you.

berndy2001
  • 64
  • 6
  • You should convert the date to YYYY-MM-DD and put that in a hidden element in front of the visible date. Then the alpabetical sort will work. You can do the conversion with plain javaScript using `Date()`, no nood for `moment` here. – lofihelsinki Feb 16 '18 at 07:01
  • @lofihelsinki Thank you for the input, I appreciate it. But it isn´t working out for me, I made a jsfiddle https://jsfiddle.net/L7e81jhr/12/ – berndy2001 Feb 16 '18 at 09:15

1 Answers1

1

Update: See Edit 2 below that answers the actual question.

Seems like adding sort_as: 'alphaNum' to the yadcf parameters of the date column would do it:

$(document).ready(function(){
  $.fn.dataTable.moment( 'DD.MM.YYYY' );
  $('#test').dataTable().yadcf([
    {column_number : 0, select_type: 'select'},
    {column_number : 1, select_type: 'select', sort_as: 'alphaNum'}
  ]);
});

EDIT: If you also want to change the default sorting to the date column, you need add orderparam to the dataTablesobject itself:

$(document).ready(function(){
  $.fn.dataTable.moment( 'DD.MM.YYYY' );
  $('#test').dataTable({
    "order": [[ 1, 'asc' ]]
  }).yadcf([
    {column_number : 0, select_type: 'select'},
    {column_number : 1, select_type: 'select', sort_as: 'alphaNum'}
  ]);
});

EDIT 2: If you want to sort the yadcf select/dropdown, the only option i see is having your own sorting function:

$(document).ready(function(){
  $.fn.dataTable.moment( 'DD.MM.YYYY' );
  $('#test').dataTable({
    "order": [[ 1, 'asc' ]]
  }).yadcf([
    {column_number : 0, select_type: 'select'},
    {column_number : 1, select_type: 'select', sort_as: 'custom', sort_as_custom_func: function(one, two) {
        if (moment(one, "DD.MM.YYYY").isAfter( moment(two, "DD.MM.YYYY") )) {return true}
        else {return false}
      }
    }
  ]);
});
lofihelsinki
  • 2,491
  • 2
  • 23
  • 35