How to get dd-mm-yyyy format date in datatable laravel - javascript

I get the serverside data from controller, and get data using ajax. This is my datatable script.
// Data table
var table = $('.data-table').DataTable({
processing: true,
serverSide: true,
responsive: true,
ajax: "quotation",
dom: '<"top"fB>rt<"bottom"lip><"clear">',
columns: [{
data: 'quotation_no',
name: 'quotation_no'
},
{
data: 'remarks',
name: 'remarks'
},
{
data: 'quotation_date',
name: 'quotation_date'
},
{
data: 'quotation_category',
name: 'quotation_category'
},
{
data: 'quotation_status',
name: 'quotation_status'
},
{
data: 'action',
name: 'action',
orderable: false,
searchable: false
},
],
"lengthMenu": [
[10, 25, 50, -1],
[10, 25, 50, "All"]
],
});
default format for quotation_date is yyyy-mm-dd . How to make dd-mm-yyyy?

You can do something like this in the Model.
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'quotation_date' => 'datetime:d-m-Y',
];
Or, alternatively you can also use Carbon Date in the controller:
$quotationDate = Carbon::parse($item['quotation_date'])->format('d-m-Y');

Just add in your model $casts attr if you use eloquent for getting data from DB.
protected $casts = [
'quotation_date' => 'datetime:d-m-Y',
];
After it action your date format will be like dd-mm-yyyy

Related

Show json value in jquery ajax datatables result

I add json data in database like this (in database column social):
{"twitter":"test","instagram":"test1","linkedin":"test2"}
for show result in datatables:
var tableUser = $('#table-user').DataTable({
dom: 'rt<"card-footer"<"row" <"col-md-6"i> <"col-md-6"p>>>',
processing: true,
serverSide: true,
autoWidth: false,
order: [
[1, 'asc']
],
ajax: {
url: '<?= route_to('admin/user/manage') ?>',
method: 'GET'
},
columnDefs: [{
orderable: false,
targets: [0, 4, 5]
}],
columns: [
{
'data': function(data) {
return data.social
},
}
]
});
Result is(return data.social):
{"twitter":"test","instagram":"test1","linkedin":"test2"}
In action I need to specific value like: twitter or instagram. How to show this result?!

How to JS Date Format

I'm using Laravel 8 and Bootsrap in this project. I've tried to solve this problem with Carbon in Laravel, but the prob still likes that.
So I think maybe the problem in JS Script, but I dunno about JS so deep. I really need help with this prob.
My problem is how to change the date format in JS, I wish to change in DD/MM/YYYY format.
JS Script
<script>
$(function() {
$('#kategoris-table').DataTable({
processing: true,
serverSide: true,
ajax: 'kategori/json',
columns: [
{ data: 'id', name: 'id' },
{ data: 'nama', name: 'nama',
fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
$(nTd).html("<a href='/kategoris/"+oData.id+"'>"+oData.nama+"</a>");
}
},
{ data: 'updated_at', name: 'updated_at'},
]
});
});
</script>
My Table View
Add this variable to the Model class:
protected $casts = [
'updated_at' => 'datetime:m/d/Y'
];
This will change the datetime format and will reflect whenever you retrieve the data through eloquent.
You could try registering an editor and using moment.js. Something like this:
var editor; // use a global for the submit and return data rendering in the examples
$(document).ready(function() {
$.fn.dataTable.moment( 'DD/MM/YYYY' );
editor = new $.fn.dataTable.Editor( {
ajax: 'kategori/json',
table: '#kategoris-table',
fields: [ {
label: 'Updated at:',
name: 'updated_at',
type: 'datetime',
def: function () { return new Date(); },
format: 'DD/MM/YYYY',
fieldInfo: 'Formatted date'
}
]
} );
$('#kategoris-table').DataTable({
processing: true,
serverSide: true,
ajax: 'kategori/json',
columns: [
{ data: 'id', name: 'id' },
{ data: 'nama', name: 'nama',
fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
$(nTd).html("<a href='/kategoris/"+oData.id+"'>"+oData.nama+"</a>");
}
},
{ data: 'updated_at', name: 'updated_at'},
]
});
});
Please see this example which includes the other libraries you would need to load at the end of the example: https://editor.datatables.net/examples/dates/formatting.html
PS - I tried to include the libraries in my answer in case of a broken link but when I do, I am given the message that "There appears to be code in my post that is not formatted properly" and I cannot seem to get it to work with formatting the links.

How to change the format of a date field in a jsgrid table

Good afternoon, I have this data in a jsgrid table, the fact is that when the database returns the date when displaying it on the page it looks like this: / Date (1614232800000) / what I need is to convert it to DD format / MM / YYYY
Reading the official documentation, there is by default a type of date field as such, but it is possible to modify parameters at will, that being the case, how can I convert the date?
I read all from this, any idea, thank you.
http://js-grid.com/docs/#custom-field
First of all, Thanks.
var MyDateField = function (config) {
jsGrid.Field.call(this, config);
};
MyDateField.prototype = new jsGrid.Field({
css: "date-field", // redefine general property 'css'
align: "center", // redefine general property 'align'
myCustomProperty: "itemTemplate", // custom property
itemTemplate: function (value) {
return new Date(value).toDateString();
}
});
jsGrid.fields.date = MyDateField;
$('#dgrecordsfound').jsGrid({
width: "100%",
height: "350px",
filtering: false,
inserting: false,
editing: false,
sorting: true,
paging: true,
autoload:true,
pageButtonCount: 5,
noDataContent:"No records!",
loadIndication: true,
loadMessage: "Loading, Please wait",
pagercontainer:null,
pageIndex: 1,
pageSize: 6,
pageButtonCount: 15,
pagerFormat: "Pages: {first} {prev} {pages} {next} {last} {pageIndex} de {pageCount}",
pagePrevText: "Prev",
pageNextText: "Next",
pageFirstText: "First",
pageLastText: "Last",
pageNavigatorNextText: "...",
pageNavigatorPrevText: "...",
controller: {
loadData: function () {
return $.ajax({
type: "GET",
datatype: "json",
data: { parname: "#ViewBag.name" , parlastname: "#ViewBag.lastname"},
url: "/asoc/getbyname"
});
},
},
fields: [
{
name: "cod",
title: "Code",
type: "text",
width: 30
},
{
name:"firstname",
title: "firstname",
type: "text",
width: 100
},
{
name: "date",
title: "Date",
type: "date",
myCustomProperty: "itemTemplate",
width: 30
}
],
rowClick: function (itemselected) {
var getdata = itemselected.item;
var fields = Object.keys(getdata);
var textarray = [];
$.each(fields, function (idx, value) {
textarray.push(getdata[value])
});
var url = '#Url.Action("index", "request")' + '/id=1?parCod='+ textarray[1];
window.location.href = url;
}
});

Jquery datatables amount of pages

I'm trying to use jquery datatables with backend on Spring HATEOAS which returns HAL document with structure:
{
"_embedded": {...},
"_links": {...},
"page": {
"size": 10,
"totalElements": 15,
"totalPages": 2,
"number": 0
}
}
Currently my datatable settings looks like:
const table = TABLE_ELEMENT.DataTable({
processing: true,
ordering: false,
serverSide: true,
paging: true,
pagingType: 'numbers',
pageLength: 10,
lengthChange: false,
recordsTotal: 15,
searching: false,
ajax: {
type: 'GET',
url: '/api/employees',
dataSrc: data => data._embedded.employees,
},
columns: [
{data: 'name'},
{data: 'email'},
{data: 'phone'},
{data: 'birthDay'}
]
});
But the problem is that I can't properly setup number of pages I have. If I use serverSide: true my table has infinite amount of pages, if i use serverSide: false instead my table has only 1 page. How to solve this?
To switch between pages I use code:
TABLE_ELEMENT.on('page.dt', () => {
table.ajax.url('/api/employees?page=' + table.page.info().page);
});
to solve this I replaced property dataSrc, with:
dataFilter: (data) => {
let json = JSON.parse(data);
json.recordsTotal = json.page.totalElements;
json.recordsFiltered = json.page.totalElements;
json.pageLength = json.page.size;
json.data = json._embedded.employees;
return JSON.stringify(json);
}
also properties
pageLength: 10,
recordsTotal: 15
can be removed

How can I load rows in JsGrid table that got from php file?

I tried to load rows of data from a table in MySQL. I used jsgrid with PHP.
My two php files connect to the localhost datanase and select rows from the tables using mysqli functions, and copy the result of the query into an array and send by json_encode() to an HTML file where I put the jsgrid code.
Then, I call the html file into other PHP file by <iframe> html tag.
The names of PHP files are:
newsConf, controll and getnewscat
HTML file: basic.html
in controll.php:
public function newsConfig(){
$this->CONN = new Conn();//class from external page to connect DB
try{
$dfnet = $this->CONN->open_connect();
$qnco = mysqli_query($dfnet,"select * from category");
if(!$qnco) return "";
else{
while($qncoarray = mysqli_fetch_row($qnco)){
//here I try copy rows into array
$nnopCo[] = array(
'ID' => $qncoarray['ID'],
'Name' => $qncoarray['Name']
);
}
return $nnopCo;
}
$this->CONN->close_connect($dfnet);
}
catch(Exception $er){
}
in getnewscat.php:
<?php require_once "../../bin/controll.php";
$db_controll = new Controll();
$cat_news = new ArrayObject($db_controll->newsConfig());
header('Content-type: application/json');
echo json_encode($cat_news->getArrayCopy());
?>
in basic.html: is the same file from jsgrid demo, but I change the code in javascript and canceled the db.js file
$(function() {
$("#jsGrid").jsGrid({
height: "70%",
width: "50%",//100%
selecting: false,
filtering: false,
editing: false,
sorting: false,
paging: true,
autoload: true,
pageSize: 15,
pageButtonCount: 5,
controller: {
loadData: function(clients){
var d = $.Deferred();
$.ajax({url: "../bin/getnewscat.php", dataType: "json",function(obj){
for (var i = 0; i < obj.length; i++) {
/*res[i]=data.i;
i++;*/
clients = {
"ID": obj.ID,
"Name": obj.Name
};
}
}
}).done(function(response) {
d.resolve(response.value);
});
return d.promise();
}
In newsConf.php: that file should call basic.html and give the result
by this:
<iframe name="demo" src="jsgrid-1.2.0/demos/basic.html"></iframe>
But the result is empty and I don't know why?, however I change the code but it didn't yield success.
What have I missed here?
Update
See my update below.
The done function should work. Remove success handler and put your mapping into done handler. Then put a debugger into done handler to ensure what you get in a response. Then map the response accordingly and resolve the deferred.
loadData: function(clients){
var d = $.Deferred();
$.ajax({
url: "../bin/getnewscat.php"
}).done(function(response) {
// put a debugger here to ensure that your response have 'value' field
var clients = $.map(response.value, function(item) {
return {
ID: item.SomeID,
Name: item.SomeName
};
});
d.resolve(clients);
});
return d.promise();
}
I'm not sure whether you need a mapping or not. Maybe you can remove it in the end. But do everything in the done handler and check the format of the response.
Sorry for my delay, but I think I got where's my mistake!
I fixed it and I got what I missed,
In controll.php file, I used mysqli_fetch_row() function, but I forgot I send the data in a named array, so I changed it to mysqli_fetch_assoc() function.
and about basic.html I changed it to:
<script>
$(function() {
{
$("#jsGrid").jsGrid({
height: "70%",
width: "50%",//100%
selecting: false,
filtering: false,
editing: false,
sorting: false,
paging: true,
autoload: true,
pageSize: 15,
pageButtonCount: 5,
controller: {
loadData: function(filter) {
//here how I fix it!
return $.ajax({url: "../bin/getnewscat.php",data:filter
});
}
},
////////////////////////////////////////////////////////////
fields: [
{ name: "ID", type: "number", width: 50 },
{ name: "Name", type: "text", width: 50},
{ type: "control", modeSwitchButton: false, deleteButton: false }
]
});
$(".config-panel input[type=checkbox]").on("click", function() {
var $cb = $(this);
$("#jsGrid").jsGrid("option", $cb.attr("id"), $cb.is(":checked"));
});
});
</script>
but I think it's not secure, how could I make it more secure?
I was having the same issue. However once I added the return to $.ajax line all I get is blank lines but the grid is trying to render something. See image below.
PHP Code Below:
$sql = "SELECT e.estimateid, e.customerid, e.compid, cu.first_name,cu.last_name,e.reference_num, e.estimate_date, e.expiry_date, e.hours, e.sales_person, e.project_name
FROM estimates AS e INNER JOIN company AS c ON e.compid = c.compid
INNER JOIN customers AS cu ON e.customerid = cu.customerid";
$resultsE = $conn->query($sql);
$rows = array();
while ($r = $resultsE->fetch_assoc()){
$rows[] = $r;
}
$data = array($rows);
}
//header("Content-Type: application/json"); //If I uncomment this line the Grid says No Results.
echo json_encode($data);
JS Code Below:
$(function() {
$("#jsGrid").jsGrid({
height: "90%",
width: "98%",
filtering: true,
inserting: false,
editing: false,
sorting: true,
paging: true,
autoload: true,
pageSize: 10,
pageButtonCount: 5,
//deleteConfirm: "Do you really want to delete client?",
controller: {
loadData: function(filter) {
return $.ajax({url: "/js/jsgrid/estimates/index.php",data: filter });
},
/*insertItem: function(item) {
return $.ajax({
type: "POST",
url: "/estimates/",
data: item
});
},
updateItem: function(item) {
return $.ajax({
type: "PUT",
url: "/estimates/",
data: item
});
},
deleteItem: function(item) {
return $.ajax({
type: "DELETE",
url: "/estimates/",
data: item
});
}*/
},
fields: [
{ name: "estimateid", type: "number", width: 10, title: "EstId" },
{ name: "customerid", type: "number", width: 10, title: "CustId" },
{ name: "compid", type: "number", width: 10, title: "CompId"},
{ name: "first_name", type: "text", width: 50, title: "First Name" },
{ name: "last_name", type: "text", width: 50, title: "Last Name" },
{ name: "reference_num", type: "text", width: 12, title: "Ref.#" },
{ name: "estimate_date", type: "text", width: 12, title: "Est. Date" },
{ name: "expiry_date", type: "text", width: 12, title: "Exp. Date" },
{ name: "hours", type: "number", width: 10, title: "Hours" },
{ name: "sales_person", type: "text", width: 50, title: "Sales" },
{ name: "project_name", type: "text" , width: 50, title: "Project"},
{ type: "control" }
]
});
});

Categories

Resources