I am trying to convert the default date time format returned from a RepositoryRestResource in Spring Boot to a human readable format in jQuery Datatables. I found this Datatables plugin:
DataTables datetime plugin
I'm using it but getting "Invalid date"
I believe I need to specify the input date format to the plugin so moment.js can understand it to do the conversion but I'm not sure how to format the input format.
Here is my javascript DataTable script:
$('#invoices').DataTable({
"bFilter": true,
"autoWidth": true,
"processing": false,
"ajax": _link,
"sAjaxDataProp" : "_embedded.invoices",
"oLanguage": {
"sSearch": "<span>Filter:</span> _INPUT_" //search
},
columnDefs: [ {
targets: 0,
render: $.fn.dataTable.render.moment( 'YYYY-MM-DD' )
} ],
"columns": [
{ "data": "dropoff"},
{ "data": "ready" },
{ "data": "total_quantity" },
{ "data": "total_price" },
{ "data": "paid" }
]
});
Here's example of the service object data: _embedded.invoices
_embedded: {
invoices: [
{
dropoff: "2016-02-13T18:00:00.000+0000",
ready: "2016-02-15T14:00:00.000+0000",
note: "ZIPPER IS NIKEL",
paid: true,
total_price: 79.8,
total_quantity: 203,
_links: {
self: {
href: "http://localhost:8080/invoices/1"
},
invoice: {
href: "http://localhost:8080/invoices/1"
},
itemlines: {
href: "http://localhost:8080/invoices/1/itemlines"
},
customer: {
href: "http://localhost:8080/invoices/1/customer"
}
}
}
So you can see the date format above: "2016-02-15T14:00:00.000+0000"
It has the full date, time, and utc offset. I just want it to show date and time without seconds, something simple doesn't need to be fancy, just clean it up a little remove the T and UTC garbage at the end for the end users.
Appreciate the help!!!
For my HTML scripts I have them in this order, which doesn't seem to be causing a problem but here it is just in case:
<script src="/js/jQuery-2.2.3/jquery-2.2.3.js"></script>
<script src="/js/datatables.js"></script>
<script src="/js/datetime.js"></script>
<script src="/js/moment.js"></script>
I would suggest you define bean for Jackson configuration:
#Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
Jackson2ObjectMapperBuilder b = new Jackson2ObjectMapperBuilder();
b.indentOutput(true).dateFormat(new SimpleDateFormat("yyyy-MM-dd"));
return b;
}
For more info check how to Customizing the Jackson ObjectMapper: With Spring Boot.
Related
I've been try to send current page number to server by overwrite a variable called pgno
here is my code :
function fill_datatable(status='',pgno='')
{
var pgno = 0;
table = $('.tb_scoin_available').DataTable({
"processing": true,
"serverSide": true,
"ordering" : false,
"infoCallback": function( settings, start, end, max, total, pre ) {
var api = this.api();
var pageInfo = api.page.info();
pgno = pageInfo.page+1;
return pgno;
},
"ajax":{
"url": base_url+'/adminPath/management_scoin/ajaxGetScoinAvailable',
"type": "POST",
"data":{ _token: csrf_token, status : status,pgno : pgno}
},
"columnDefs": [ { orderable: false} ],
"columns": [
{ "data": "no" },
{ "data": "created_at" },
{ "data": "serial_scoin" },
{ "data": "unit_scoin" },
{ "data": "unit_scoin_desc" },
{ "data": "unit_scoin_sc" },
{ "data": "unit_scoin_idr" },
],
});
}
when I try to alert on infoCallback :
alert(pgno) the variable already overwrited, but when I try to dump the request on backend the pgno POST give me null result like this :
Anyone can help me out ?
You can get the table page with the page() function, no need for the whole "page.info". It's better explained in Datatable's API: https://datatables.net/reference/api/page()
The method you're trying to access is only to get the information, not to set it. That is probably why it isn't working. Check their docs for better understanding of their API: https://datatables.net/reference/api/page.info()
EDIT:
You can get the current page through a simple calculation. Since you're using serverSide processing, you already have start and length. You just need to do start/length + 1 and you will get the current page number.
DataTable initialisation, give it the server url location
oTable = $('.entrys_table').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "entrys_table_server_side_source",
"type": "POST"
},
"language": {
"infoFiltered": " - filtered from _MAX_ records"
},
"columns": [
{ data: "engine" },
{ data: "browser" },
]
})
yadcf.init(oTable, [
{
column_number: 0,
filter_container_id: 'account1',
filter_type: 'select',
},
{
column_number: 1,
filter_container_id: 'account2',
filter_type: 'select',
},
], { externally_triggered: true });
But I would like to ask how to make yadcf URL location is different?
More hope is that each option can have a separate URL location?
And let the option can be updated independently of the data (again to the server to get the latest information)
Any help is appreciated.
The only possible way that can I think of is to use yadcf along with third party select plugin (chosen / select2) and load its data using ajax
Something like Jquery Chosen plugin - dynamically populate list by Ajax or Select2 Ajax (remote data)
In addition please take a look at the following issue that was eventually resolved and looks like it might be useful for you
ajax populated fields + externally_triggered + server_side removing fields value
I have some data coming as a timestamp so I need to format it before it goes to the end user. I didn't found any way to achieve this using a predefined formatter from jQgrid.
Having said that I am trying to use a mix of "native" Javascript and MomentJS to format the data before display it.
The first thing I did was load the library momentjs before load jqgrid:
<script src="js/jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="js/jquery-migrate-3.0.1.min.js" type="text/javascript"></script>
<script src="js/moment.min.2.20.1.js" type="text/javascript"></script>
<script src="js/free-jqgrid/jquery.jqgrid.min.js" type="text/javascript"></script>
Next I have created a custom formatter to be used in that column:
$.extend($.fn.fmatter, {
customTimestampToDate: function (cellvalue, options, rowdata) {
var parsed_timestamp = parseInt(rowdata.timestamp),
tmp = new Date(parsed_timestamp * 1000).toISOString();
console.log(typeof cellvalue); // logs string
console.log(typeof rowdata.timestamp); // logs string
console.log(typeof parsed_timestamp); // logs "number"
console.log(tmp); // logs 2018-01-15T14:19:28.000Z
return moment(tmp);
}
});
Last I have tried to use the custom formatter in the colModel:
colModel: [
{name: "act", template: "actions", width: 115},
{name: "username", search: true, stype: "text"},
{name: "email", search: true, stype: "text"},
{name: "first_name", search: true, stype: "text"},
{name: "last_name", search: true, stype: "text"},
{name: "company", search: true, stype: "text"},
{name: "request_uri", search: true, stype: "text"},
{name: "client_ip", search: true, stype: "text"},
{
name: "timestamp",
search: true,
stype: "text",
formatter: "customTimestampToDate"
}
],
For some reason I am getting the timestamp value instead of the formatted one and I am not sure why or how.
I have been playing with momentjs on this Fiddle and it works as expected. I have been playing also with momentjs inside jqgrid in this Fiddle and as I am showing here is not working.
The problem: the issue here is the value being displayed as a string|int at timestamp column after the grid render which means the value on the column is the timestamp. The expected value would be the formatted one by moment doesn't matter if it's properly formatted or not (that's another different issue).
My guess is that the library hasn't been loaded when the grid is constructed or something like that but I am not sure at all.
Any ideas?
Note: Maybe there is an easy way to achieve this using a predefined formatter but I couldn't find it, if you know it let me know
To display timestamps in jqGrid you can use predefined formatter "date" instead of the custom formatter: "customTimestampToDate". You can replace
formatter: "customTimestampToDate"
to, for example,
formatter: "date", sorttype: "date",
formatoptions: {srcformat: "u", newformat: "n/j/Y g:i:s A"}
The srcformat could be "u" or "u1000" depend on which timestamp you have as input. The default value of newformat is "n/j/Y", but you can change it to another one. You should use PHP formatting syntax (see http://php.net/manual/en/function.date.php).
It's recommended to use custom formatters only if predefined formatters can't do what you need. You can use moment plugin for example for advanced formatting of dates. You should don't forget to define unformatter (unformat callback function) always if you define formatter. It's required for editing of the data for example.
As the docs says:
To print out the value of a Moment, use .format(), .toString() or .toISOString().
Your code could be like the following:
customTimestampToDate: function (cellvalue, options, rowdata) {
var parsed_timestamp = parseInt(rowdata.timestamp),
tmp = new Date(parsed_timestamp * 1000).toISOString();
return moment(tmp).format();
}
You can pass a format token to format() or use toISOString() to the the output in ISO 8601 compliant string.
Note that moment accepts also Unix timestamps in seconds, so you can use moment.unix(Number), in your case: return moment.unix(rowdata.timestamp).format();
You do not need to use moment. Just use srcformat u (which is Unix timestamp) and the grid will do the job
formatter : 'date', formatoptions : {
srcformat : 'u',
newformat : 'Y-m-d H:i:s'
}
I have a kendo scheduler and I'm having a problem with move event. I can move only one event at a time and then I can't even grab any event afterwards. I think there's something wrong with the dates but I really can't figure out why. I tried dataSource with 2-3 events and it's working but when I put that exact same data in php and return it as json. It's not working.
Any help would be appreciated.
$("#scheduler").kendoScheduler({
date: new Date(),
startTime: new Date(today2()),
timezone: "Etc/UTC",
currentTimeMarker: false,
height: 800,
views:
[
"week",
{ type: "month", selected: true, eventHeight: 60}
],
dataSource:
{
transport:
{
read:
{
url: "tasks.php",
dataType: "json"
},
batch: true,
parameterMap: function (options, operation)
{
if (operation === "read") {
var scheduler = $("#scheduler").data("kendoScheduler");
var result =
{
start: scheduler.view().startDate(),
end: scheduler.view().endDate()
}
return kendo.stringify(result);
}
return kendo.stringify(options);
}
},
schema:
{
model:
{
id: "taskId",
fields:
{
taskId: { type: "number", from: "TT_CODE" },
start: { type: "date", from: "TT_START_DATETIME"},
end: { type: "date", from: "TT_END_DATETIME"},
title: { from: "TT_EDIT"}
}
}
}
}
});
php file with json data:
$json[0]['TT_CODE'] = 1;
$json[0]['TT_START_DATETIME'] = "2016-01-16 15:00:00";
$json[0]['TT_END_DATETIME']= "2016-01-16 16:00:00";
$json[0]['TT_EDIT'] = "Fast and furious 6";
echo json_encode($json);
Since you specified start and end as date in your model, the scheduler is expecting to received properly formatted date. While JSON passes date as string, javascript still expect the date string to be formatted.
In your case, it would be:
$json[0]['TT_CODE'] = 1;
$json[0]['TT_START_DATETIME'] = "2016-01-16T15:00:00.000Z";
$json[0]['TT_END_DATETIME']= "2016-01-16T16:00:00.000Z";
$json[0]['TT_EDIT'] = "Fast and furious 6";
You could also leave date as is and handle the string with a custom logic in the parameterMap function.
As a side note, if you have a doubt about the type formatting, go in the browser console and have a look at the network tab. You'll be able to compare the data sent by the working service to the data sent by PHP and see where is the difference.
Why is rows() not a function on a server-side datatable?
The tables works fine beside that.
I have used rows() on five other client-side datatables before without any problems.
var tableComputerAndDevice = $('#tableComputerAndDevices').dataTable({
searching: true,
processing: true,
serverSide: true,
language: {
"processing": '<div style="background-color:#eee"> <span class="fa fa-spinner fa-pulse fa-5x"> </span> </div>'
},
ajax: {
url: url,
data: data,
type: "POST"
},
columns: [
{ "data": "checkbox", "searchable": false },
{ "data": "ComputerName", "searchable": true },
{ "data": "LastContact", "searchable": true }
]
});
var nodes = tableComputerAndDevice.rows('.selected').nodes();
console.log('nodes: ' + nodes);
Error: TypeError: tableComputerAndDevice.rows is not a function
Yes you judged it correctly. You need to change the dataTable to DataTable
Also to state that there is a difference between dataTable and DataTable.
The difference between the two is that the first will return a jQuery
object, while the second returns a DataTables API instance.
Change dataTable to DataTable. I answer my own question because I spent a hour with this bug, so I hope I can help others.
var tableComputerAndDevice = $('#tableComputerAndDevices').DataTable({