How To Use A Plug-in?
How To Use A Plug-in?
Hi,
I have been struggling to get a date column in my datatable to sort correctly. After searching through the site I found an example plug-in on the blogmaking use of moment.js which looks like it should do the job. I'm already using moment.js elsewhere in my code, so this plug-in should be ideal for my needs. My only problem is that I'm not sure how I get my datatable to make use of this plug-in and it's not clear from the page on the blog (https://datatables.net/blog/2014-12-18). Sorry for the newbie question.
My datatable definition looks like this:
bookingsdatatable = $('#bookings').DataTable({
data: bookings_array,
dom: "Bfrtip",
stateSave: true,
columns: [
{ data: 'id', visible: false},
{ data: 'jobId'},
{ data: 'venueId'},
{ data: 'bookingDate'},
{ data: 'bookingTime',"bSearchable": false},
{ data: 'catalogue', "bSearchable": false},
{ data: 'wsn', visible: false},
{ data: 'win', visible: false},
{ data: 'commision', visible: false}
],
select: true,
buttons: [
{ extend: "edit", editor: editor },
{ extend: "remove", editor: editor }
]
});
and the plug-in code is:
$.fn.dataTable.moment = function ( format, locale ) {
var types = $.fn.dataTable.ext.type;
// Add type detection
types.detect.unshift( function ( d ) {
return moment( d, format, locale, true ).isValid() ?
'moment-'+format :
null;
});
// Add sorting method - use an integer for the sorting
types.order[ 'moment-'+format+'-pre' ] = function ( d ) {
return moment( d, format, locale, true ).unix();
};
};
My problem is that I don't know how to get the one to use the other.
Help!
Thanks in advance.
This question has an accepted answers - jump to answer
Answers
Include the plug-in code first (or in a file that is included after DataTables' own JS, but before you initialise the table).
Then you need to tell the plug-in what format to use:
Allan
Is there something I have to do within the column definitions to use this format?
At the moment the relevant column just has
and it is showing up as the unix timestamp as stored in the db rather than the formatted date.
No. It will automatically detect columns with the date format that you give.
The plug-in I linked to won't format the date, rather it deformats a formatted one to allow sorting!
If you want to convert a timestamp into a readable value, then this plug-in is the one you want. It is a renderer that uses Moment to display date information.
Allan
Oh yes, I see.
Now working, so many thanks.