I have a web app with cloud firestore as my backend. I used DataTable to export data from cloud firestore and display on the webpage, and the table looks like this:
Table
The code to load "orders" collection from cloud firestore and append to DataTables is:
var dataTable;
db.collection("orders").orderBy('timestamp', 'desc')
.get()
.then(function (querySnapshot) {
if (querySnapshot.size) {
var firestore_source = [];
querySnapshot.forEach(function (data) {
var obj = data.data();
obj.id = data.id;
firestore_source.push(obj);
});
//console.log('data:', firestore_source);
dataTable.clear();
dataTable.rows.add(firestore_source);
dataTable.order([0, 'desc']).draw();
}
})
.catch(function (error) {
console.log("Error getting documents: ", error);
});
$(document).ready(function () {
dataTable = $('#example').DataTable({
columns: [
{ data: 'Name' },
{ data: "Date" },
{ data: "Ins" },
{ data: "Phone" },
{ data: "Item" },
{ data: "Price"},
{ data: "Commision"},
{ data: "Revenue"},
{
data: null,
className: "center",
defaultContent: 'Edit / Delete'
}
],
"columnDefs": [
{"className": "dt-center", "targets": "_all"}
],
});
$('#example').on('click', 'a.editor_remove', function (e) {
e.preventDefault();
console.log("delete clicked");
console.log($(this).closest('tr'));
// what I should do here?
} );
});
And datatables in HTML:
<table id="example" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>Customer</th>
<th>Order Date</th>
<th>Instagram</th>
<th>Phone</th>
<th>Item</th>
<th>Price $</th>
<th>Commission</th>
<th>Earnings $</th>
<th>Edit / Delete</th>
</tr>
</thead>
</table>
Currently, the entire data within "orders" collection is loaded and obviously there are no features like editing and deleting data in each row.
So, I am stuck here that I have no idea how to identify each row in my table when clicking the edit/delete buttons on that row, so that I can use it as parameters to query cloud firestore?
I saw that there is built in tool Editor, but I am looking for native methods.
Regarding datatable API, You can get the clicked/selected row's data by this code which means you can get identity to edit or remove the selected row.
$('#example tbody').on('click', 'a.editor_remove', function () {
let row = dataTable.api().row($(this).closest("tr")).data();
console.log(row);
});
Related
I want to use the jquery pluging datatables and complement local data through an external REST ressource.
My table has to columns, Id and RestCalledValue:
<table id="table">
<thead>
<tr>
<th>Id</th>
<th>RestCalledValue</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
My js has an object data, which holds my local data:
let data = [
{
"id": 1
},
{
"id": 2
}
]
My datatables initialisation looks like below: i want to give the second column the returned value from the function getRestDataForId (id).
$(function () {
var table = $('#table').DataTable({
data: data,
columns: [
{
data: "id"
},
{
data: function (row, type, set, meta) {
getRestDataForId(row.id);
},
defaultContent: "-"
}
]
});
});
function getRestDataForId(id) {
fetch('https://jsonplaceholder.typicode.com/todos/' + id)
.then(response => response.json())
.then(data => data.title)
}
I constructed a fiddle here:
https://jsfiddle.net/mxhdwfz6/2/
I must be treating the promise wrong. Looking forward for your input!
The following code samples demonstrates how I initialize a jQuery Datatable with HTML, knockout and typescript
HTML:
<table id="coursemoment-info-table" class="table table-hover">
<thead>
<tr >
// headers
</tr>
</thead>
<tbody>
<!-- ko foreach: selectedCourseMoment().courseApplications -->
<tr>
<td>
<a data-bind="{text: ssn, attr:{ href: '/Medlem/' + ssn} }"></a>
</td>
<td data-bind="text:name + ' ' + surname"></td>
.
.
.
</tr>
<!-- /ko-->
</tbody>
</table>
Typescript:
private initCourseMomentInformationDataTable(): void {
$("#coursemoment-info-table").DataTable({
pageLength: 5,
order: [1, 'desc'],
language: {
url: "/Assets/js/jquery-datatable-swedish.json"
}
});
}
I have had some problems with reinitializing the table, but I managed to handle it with first clearing the datatable, and then adding rows to the datatable and redraw it.
if (this.tableInitiliazed) {
$("#coursemoment-info-table").DataTable().clear().draw();
for (var i = 0; i < data.courseApplications.length; i++) {
var application = data.courseApplications[i];
$("#coursemoment-info-table").DataTable().row.add(
[
application.ssn,
// blah blah yada yada
]).draw();
}
This does indeed reinitiliaze the datatable, but it does not put a hyperlink to the first column as it does when initializing the table. All the other table settings are correct, such as language and pagelength.
Since I add one row at a time, with the multiple columns I do not know how to set column settings for "applications.ssn" directly. I have tried to initialize the datatable in the viewmodel with typescript but I get the same problem.
Any ideas how to reinitialize and put a hyperlink setting for a specific column?
I think you want to use Datatables render to create your link. so here is a custom data binder for data table that uses render to create the link.
here is the fiddle to see it in action. http://jsfiddle.net/LkqTU/35823/
ko.bindingHandlers.dataTable = {
init: function(element, valueAccessor, allBindingsAccessor) {
var value = valueAccessor(),
rows = ko.toJS(value);
allBindings = ko.utils.unwrapObservable(allBindingsAccessor()),
$element = $(element);
var table = $element.DataTable( {
data: rows,
columns: [
{ data: "id" },
{ data: "firstName" },
{ data: "lastName" },
{ data: "phone" },
{
data: "ssn",
"render": function ( data, type, full, meta ) {
return '<a href="/Medlem/'+data+'">' + data + '<a>';
}
}
]
} );
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$element.dataTable().fnDestroy();
});
value.subscribe(function(newValue) {
rows = ko.toJS(newValue)
console.log(rows);
$element.find("tbody tr").remove();
table.rows().remove().draw();
setTimeout(function(){ $.each(rows, function( index, row ) {
table.row.add(row).draw()
});
}, 0);
}, null);
}
}
I am using bootstrap datatable to make a simple presentation of my json. I am using this json to feed datatable :
{
"manualList":[
{
"number":"WFC2062/05",
"umtype":"PT,SI",
"lang":"DE",
"cdnlink":"http://medias.bsh-partner.com/Documents/5550009686_A.pdf",
"version":"A",
"filelenght":1002357,
"urlstatus":true
},
{
"number":"WFC2062/05",
"umtype":"II,IU",
"lang":"DE",
"cdnlink":"http://medias.bsh-partner.com/Documents/5550009685_B.pdf",
"version":"B",
"filelenght":6377032,
"urlstatus":true
},
{
"number":"WFC2062/06",
"umtype":"PT,SI",
"lang":"DE",
"cdnlink":"http://medias.bsh-partner.com/Documents/5550009686_A.pdf",
"version":"A",
"filelenght":1002357,
"urlstatus":true
},
{
"number":"WFC2062/06",
"umtype":"II,IU",
"lang":"DE",
"cdnlink":"http://medias.bsh-partner.com/Documents/5550009685_B.pdf",
"version":"B",
"filelenght":6377032,
"urlstatus":true
},
{
"number":"WFC2062/07",
"umtype":"II,IU",
"lang":"DE",
"cdnlink":"http://medias.bsh-partner.com/Documents/9000029228_C.pdf",
"version":"C",
"filelenght":5918430,
"urlstatus":true
},
{
"number":"WFC2062/08",
"umtype":"II,IU",
"lang":"DE",
"cdnlink":"http://medias.bsh-partner.com/Documents/9000029228_C.pdf",
"version":"C",
"filelenght":5918430,
"urlstatus":true
}
],
"servicetype":"vibki",
"errormessage":null,
"warning":null
}
Data is in json format and i want to show hyperlink with column number, so my aim to add a column with the text of one manualList number and hyperlink of manuaList's cdnlink. But i don't know how to refer both of them inside one column.
Here is my script that creates datatable :
$(document).ready(function() {
var link = localStorage.getItem("link_url");
var table = $('#example').DataTable( {
"ajax": {
"url": link,
"dataSrc": "manualList"
},
"columns": [
{
"data": "cdnlink",
"render" : function(data, type, row, meta){
if(type === 'display'){
return $('<a>')
.attr('href', data)
.text()
.wrap('<div></div>')
.parent()
.html();
} else {
return data;
}
}
},
{ "data": "lang" }
]
});
$('#example')
.removeClass( 'display' )
.addClass('table table-striped table-bordered');
} );
link_url is giving ajax response that i've mentioned above, so you can this example json to evaluate the response.
Here is simple HTML that includes datatable as example :
<div class="container">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Number</th>
<th>Language</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Number</th>
<th>Language</th>
</tr>
</tfoot>
</table></div>
I hope someone can help me, many thanks in advance for your responses!
I've checked below link to make column rendering on datatable :
https://datatables.net/examples/advanced_init/column_render.html
So, i've created one more invisible column to put cdnlink there and changed from columns to columnDefs such as :
$(document).ready(function() {
var link = localStorage.getItem("link_url");
var table = $('#example').DataTable( {
"ajax": {
"url": link,
"dataSrc": "manualList"
},
"columnDefs": [
{
"data" : "cdnlink",
"targets" : 2
}
,
{// The `data` parameter refers to the data for the cell (defined by the
// `data` option, which defaults to the column being worked with, in
// this case `data: 0`.
"data" : "number",
"render": function ( data, type, row ) {
return $('<a>')
.attr({target: "_blank",href: row.cdnlink})
.text(data)
.wrap('<div></div>')
.parent()
.html();
},
"targets": 0
},
{
"data" : "lang",
"targets" : 1
},
{ "visible": false, "targets": [ 2 ] }
]
});
$('#example')
.removeClass('display')
.addClass('table table-striped table-bordered');
} );
I've also added column in html file :
<div class="container">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Number</th>
<th>Language</th>
<th>Link</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Number</th>
<th>Language</th>
<th>Link</th>
</tr>
</tfoot>
</table></div>
Then it worked like charm.
I want to set a css style to the row where checkbox is clicked but am unable to do so. The code is as follows. The code for checkbox click works fine for both the select all and individual check box. I want to get the Request ID for the selected rows and send them to the database via JSON object by post method to a php script.
Possibly the row is not getting selected.
HTML:
<table id="mytable" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th><input type="checkbox" name= "check_all" id="check_all"/></th>
<th>Request ID</th>
<th>Request Date</th>
<th>Leave Type</th>
<th>Start Date</th>
<th>End Date</th>
<th>Status</th>
</tr>
</thead>
</table>
javascript
$('#mytable').DataTable({
data: msg,
columns: [
{ data: 'RequestID'},
{ data: 'RequestID' },
{ data: 'RequestDate' },
{ data: 'LeaveType' },
{ data: 'LeaveStart' },
{ data: 'LeaveEnd' },
{ data: 'Status' }
],
"columnDefs": [ {
"targets": 0,
"searchable": false,
"data": "RequestID",
"render": function ( data, type, full, meta ) {
return '<input type="checkbox" class="checkBoxClass" name= "check_id[]" data-id="'+data+'" />';
},
}]
});
$("#check_all").click(function () {
$(".checkBoxClass").prop('checked', $(this).prop('checked'));
});
$(".checkBoxClass").change(function(){
if (!$(this).prop("checked")){
$("check_all").prop("checked",false);
$('#mytable').row(this).removeClass('row_selected');
}
$('#mytable').row(this).addClass('row_selected');
});
CAUSE
There are some issues with your code:
You attach event handler directly but with jQuery DataTables only current page elements exist in DOM. Use delegated event handler instead.
You need to access row node by using $(this).closest('tr'), not $('#mytable').row(this)
Conditional statement was missing else part.
SOLUTION
Use the code below to attach delegated event handler to all checkboxes.
$("#mytable").on('change', '.checkBoxClass', function(){
if (!$(this).prop("checked")){
$("check_all").prop("checked", false);
$(this).closest('tr').removeClass('row_selected');
} else {
$(this).closest('tr').addClass('row_selected');
}
});
I am using server side processing to read the database table and convert the records into Json file, and pass it to the database table to display data.
Read database and convert it into json:
code:
Route::get('banner/list/banners/json/{id}', function ()
{
$banner = DB::table('banner_creatives')->where('Id','=','53')->get();
$recordsTotal = count($banner);
$data['draw'] = 1;
$data['recordsTotal'] = $recordsTotal;
$data['recordsFiltered'] = $recordsTotal;
$data['data'] = $banner;
return Response::json($data);
});
Json output:
{"draw":1,"recordsTotal":1,"recordsFiltered":1,"data":[{"id":1,"bId":26,"cId":53,"bName":"32_32_53.jpeg","storageType":"url","width":32,"height":32,"weight":1,"imageURL":"localhost:8000\\\/banner\\\/view\\\/32_32_53.jpeg","clickURL":"","created_at":"2015-01-26 12:32:28","updated_at":"2015-01-26 12:32:28","deleted_at":null}]}
As you can see on this json, I have the image Url that I want to display it on the table.
JavaScript code:
$(document).ready(function() {
var table = $('#banner').DataTable( {
"processing": true,
"serverSide": false,
"ajax": "banners/json/53",
"columns": [
{ "data": "id" },
{ "data": "bannerId" },
{ "data": "campaignId" },
{ "data": "bannerName" },
{ "data": "width" },
{ "data": "height" },
{ "data": "imageUrl" }
});
});
Datatable code:
<table id="banner" class="display table table-striped table-bordered table-hover dataTable no-footer" cellspacing="0" width="100%">
<thead>
<tr>
<th>id</th>
<th>Banner Id</th>
<th>Campaign Id</th>
<th>Banner Name</th>
<th>Width</th>
<th>Height</th>
<th>Image/Banner</th>
</tr>
</thead>
<tfoot>
<tr>
<th>id</th>
<th>Banner Id</th>
<th>Campaign Id</th>
<th>Banner Name</th>
<th>Width</th>
<th>Height</th>
<th>Image/Banner</th>
</tr>
</tfoot>
</table>
On the last column it displaying the image URL but is not what i want, i want to display the usually image on the datatable using the URL, if it possible.
You can use the columns.render option to specify a callback function that can modify the data that is rendered in the column.
The callback function takes three parameters (four since 1.10.1). The first parameter is the original data for the cell (the data from the db), the second parameter is the call type (filter, display, type, or sort), and the third parameter is the full data source for the row. The function should return the string that should be rendered in the cell.
In your columns definition, add the render option to your imageUrl column definition:
{
"data": "imageUrl",
"render": function(data, type, row) {
return '<img src="'+data+'" />';
}
}
Documentation on the render option found here.
Here's my solution, hope it helps someone.
{
'targets': [15,16],
'searchable': false,
'orderable':false,
'render': function (data, type, full, meta) {
return '<img src="'+data+'" style="height:100px;width:100px;"/>';
}
},
"columnDefs": [
{
// The `data` parameter refers to the data for the cell (defined by the
// `data` option, which defaults to the column being worked with, in
// this case `data: 0`.
"render": function ( data, type, row ) {
return '<img src="'+data+'" style="width=300px;height=300px;" />';
},
"targets": 1 // column index
}
]