Search code examples
datatablesyadcf

sort custom date format in yadcf plugin


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.


Solution

  • 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}
          }
        }
      ]);
    });