Search code examples
jquerytwitter-bootstrapdatedatatablesdaterangepicker

How to implement Daterangepicker with Datatables?


I need to use this date range picker with my datatables as per a business requirement. Although, a typical usage of my date range sorting and search can be seen here. https://jsfiddle.net/zy914ko6/

I need help with how to produce minimum and maximum values to have the implementation fit the required jQuery script to draw the table. FMI: I am using serverside ajax and json on my production. So far my tables are running and I do get a draw but it doesn't reflect the "effective date [3]" column.

My "somewhat" working application can be viewed here
http://live.datatables.net/pexopupu/1/edit]1

The sample of the code i used for my daterangepicker is seen here:

var table_1 = $('table.display#tb_posts').DataTable({
   "processing": true,
   "serverSide": true,
   "ajax" : {
      "url" : "{{ route('posts.list') }}",
      "type" : "GET"
   },
   "columns": [
      {data: 'check', name:'id', className: 'text-center' },
      {data: 'DT_Row_Index', name:'DT_Row_Index', className: 'text-right' },
      {data: 'id', name: 'posts.id', className: 'text-right' },
      {data: 'title', name: 'posts.title'},
      {data: 'username', name: 'users.username'},
      {data: 'created_at', name: 'posts.created_at'},
   ],
   "autoWidth": true,
   "order": [[ 3, 'asc' ]],
   "sDom": "B<<'span8'f>r>t<<'col-sm-4'i><'col-sm-8'p>>",
   "pagination": true,
   "pagingType": "full_numbers"
});
//DateRangePicker
var startdate;
var enddate;
$('#reportrange').daterangepicker({
   locale: { format: 'DD/MM/YYYY' },
   ranges: {
      'All dates' : [moment().subtract(10, 'year'), moment().add(10, 'year')],
      'Today': [moment(), moment()],
      'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
      '7 last days': [moment().subtract(6, 'days'), moment()],
      '30 last days': [moment().subtract(29, 'days'), moment()],
      'This month': [moment().startOf('month'), moment().endOf('month')],
      'Last month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
   },
   "opens": "left",
   "applyClass": "btn-primary",
   "showDropdowns": true,
},
function (start, end, label) {
   var s = moment(start.toISOString());
   var e = moment(end.toISOString());
   startdate = s.format("YYYY-MM-DD");
   enddate = e.format("YYYY-MM-DD");
});
//Filter the datatable on the datepicker apply event
$('#reportrange').on('apply.daterangepicker', function (ev, picker) {
   startdate = picker.startDate.format('YYYY-MM-DD');
   enddate = picker.endDate.format('YYYY-MM-DD');
$.fn.dataTableExt.afnFiltering.push(
function (oSettings, aData, iDataIndex) {
   if (startdate != undefined) {
      var coldate = aData[3].split("/");
      var d = new Date(coldate[2], coldate[1] - 1, coldate[1]);
      var date = moment(d.toISOString());
      date = date.format("YYYY-MM-DD");
      dateMin = startdate.replace(/-/g, "");
      dateMax = enddate.replace(/-/g, "");
      date = date.replace(/-/g, "");
      if (dateMin == "" && date <= dateMax) {
         return true;
      } else if (dateMin == "" && date <= dateMax) {
         return true;
      } else if (dateMin <= date && "" == dateMax) {
         return true;
      } else if (dateMin <= date && date <= dateMax) {
         return true;
      }
      return false;
   }
});
table_1.draw()
});

Can you help me reach a solution... I'm not sure where I went wrong.


Solution

  • Via assistance received from Datatables.net forum.

    var startdate;
    var enddate;
    
     $.fn.dataTableExt.afnFiltering.push(
     function (oSettings, aData, iDataIndex) {
     if (typeof startdate === 'undefined' || typeof enddate === 'undefined') {
     return true;
      }
      var coldate = moment(aData[3], 'DD-MM-YYYY');
       console.log('coldate', coldate)
    
       var valid = true;
    
      if (coldate.isValid()) {
       if (enddate.isBefore(coldate)) {
        console.log('enddate before coldate', enddate)
        valid = false;
       }
    
      if (coldate.isBefore(startdate)) {
      console.log('coldate before startdate', startdate)
      valid = false;
     }
      } else {
      valid = false;
     }
    
     return valid;
    
    
    
    
     });
    
    
     jQuery(document).ready(function ($) {
    
      var table;
    
      $.ajax({
      url: "table.json",
      dataType: "jsonp", // jsonp
      type: "POST",
      jsonpCallback: 'processFunction', // add this property
      contentType: "application/json; charset=utf-8",
      success: function (result, status, xhr) {
      table = $('#poview').DataTable({
        initComplete: function () {
            this.api().columns([1]).every( function () {
             var column = this;
                var select = $('<select class="custom-select custom-select-sm rowSort"><option value="">Trans Type</option></select>')
                    .appendTo( $('#rowSort' ))
                    .on( 'change', function () {
                        var val = $.fn.dataTable.util.escapeRegex(
                            $(this).val()
                        );
    
                        column
                            .search( val ? '^'+val+'$' : '', true, false )
                            .draw();
    
    
                    } );
    
    
                column.data().unique().sort().each( function ( d, j ) {
                    select.append( '<option value="'+d+'">'+d+'</option>' );
                } );
    
            });
    
    
          $('#poview_info').appendTo($('#sumInfo'));
          $('#poview_paginate').appendTo($('#pageInfo'));
    
    
        },
        "pagingType": "first_last_numbers",
        "scrollX": true,
        fixedHeader: true,
        fixedColumns: {
          leftColumns: 2
        },
        "bAutoWidth": true,
        sDom: 't<i><""p>',
        data: result,
        columns: [
            { data: 'policy number' },
            { data: 'transaction type' },
            { data: 'transaction date' },
            { data: 'transaction effective date' },
            { data: 'minimum premium amount' },
            { data: 'deferred premium amount' },
            { data: 'total written premium' },
            { data: null,
                className: "center actionItem",
                     defaultContent: '<button class="btn actionIcon" data-     toggle="modal" data-target="#modal-1"><i class="fas fa-calculator"></i></button>'}
        ],
        columnDefs: [{
          targets: -1,
    
          className: 'dt-nowrap',
          className: 'dt-left'
    
        }],
        "pageLength": 5
      });
    
       $('#reportrange').daterangepicker({
       locale: {  "format": "MM/DD/YYYY",
        "separator": " - ",
        "applyLabel": "Apply",
        "cancelLabel": "Cancel",
        "fromLabel": "From",
        "toLabel": "To",
        "firstDay": 1},
    
       "opens": "right",
       "startDate":startdate,
        },
       function (start, end, label) {
    
         console.log('New date range selected: ' + start.format('YYYY-MM-DD') 
          +   ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label   + ')');
     });
      },
        error: function (xhr, status, error) {
        console.log("Result: " + status + " " + error + " " + xhr.status + " " +            xhr.statusText);
       }
       });
    
    
    
    
      $('#reportrange').on('apply.daterangepicker', function (ev, picker) {
      startdate = moment(picker.startDate.format('DD-MM-YYYY'), 'DD-MM-YYYY');
      enddate = moment(picker.endDate.format('DD-MM-YYYY'), 'DD-MM-YYYY');
    
      table.draw();
      });
    
     });