DataTables - display a button in a cell of every row - php

I'm using the jQuery DataTables plugin and within the initialization I'm using the "drawCallback" to make changes to the look of the rows.
My code is as follows:
"drawCallback": function() {
table.rows().every( function() {
var d = this.data();
var option = this.find('.options');
if (d.activated) {
option.html('<button class="btn btn-mini btn-primary pull-right"> Enabled</button>');
} else {
option.html('<button class="btn btn-mini btn-danger pull-right"> Disabled</button>');
}
});
}
However the this.find('.options') part isn't doing anything.
Essentially I want to:
get the current row
select the column I've given the className of 'options'
insert a button there relevant to the row data
HTML:
<table id="example">
<thead>
<tr>
<th></th>
<th>Last Name</th>
<th>First Name</th>
<th>Email</th>
<th></th>
</tr>
</thead>
</table>
DataTables initialisation:
var table = $('#example').DataTable( {
columns: [
{
"className": 'center',
"data": null,
"defaultContent": ''
},
{
data: 'last_name'
},
{
data: 'first_name'
},
{
data: 'email'
},
{
"className": 'options',
"data": null,
"defaultContent": ''
}
],
// ...and so on
Originally I had the following code which worked:
$('td.options').html('<button class="btn btn-mini btn-primary pull-right"> Enabled</button>');
but this was indiscriminate of the row data and simply pasted the same button for each row.

Use columns.render option to define a function producing content for the cell.
var table = $('#example').DataTable( {
columns: [
{
"className": 'center',
"data": null,
"defaultContent": ''
},
{ "data": 'last_name' },
{ "data": 'first_name' },
{ "data": 'email' },
{
"className": 'options',
"data": null,
"render": function(data, type, full, meta){
if (full.activated) {
return '<button class="btn btn-mini btn-primary pull-right"> Enabled</button>';
} else {
return '<button class="btn btn-mini btn-danger pull-right"> Disabled</button>';
}
}
}
],
// ...and so on
});

Related

Search by Date and show data in BootstrapTable

What I want to do is to input some date time range and show me the data in a BootstrapTable. I am not able to do it.
I have two php files one is my WebSite and the other is the MySql query.
So this where I load the Input data fields and my BootstrapTabel:
<div class='col-md-2 float-left'>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Datum von:</span>
</div>
<input id="dateVon" name="dateVon" value="2022-01-01" type="text" class="form-control" placeholder="2022-01-01" aria-describedby="dateVon">
</div>
</div>
<div class='col-md-2 float-left'>
<div class="input-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Datum bis:</span>
</div>
<input id="dateBis" name="dateBis" value="2022-01-31" type="text" class="form-control" placeholder="2022-01-31" aria-describedby="dateBis">
</div>
</div>
</div>
<button id="remove" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#deleteModal" disabled>
<i class="bi bi-trash"></i> Delete
</button>
<button id="refresh" class="btn btn-primary btn-sm" onclick="refreshFunction(dateVon,dateBis);">
<i class="bi bi-trash"></i> Refresh
</button>
</div>
<div class="card-body">
<table id="table"
data-toolbar="#table-responsive"
data-search="true"
data-show-refresh="true"
data-show-toggle="true"
data-show-fullscreen="true"
data-show-columns="true"
data-show-columns-toggle-all="true"
data-detail-view="true"
data-show-export="true"
data-click-to-select="true"
data-detail-formatter="detailFormatter"
data-minimum-count-columns="2"
data-pagination="true"
data-id-field="ID"
data-page-size="50"
data-page-list="[50, 100, all]"
data-show-footer="true"
data-side-pagination="client"
data-url="verpAnrufData.php"
data-response-handler="responseHandler"
data-detail-view="true">
</table>
<script>
var $table = $('#table')
var $remove = $('#remove')
var selections = []
function getIdSelections() {
return $.map($table.bootstrapTable('getSelections'), function(row) {
return row.ID
})
}
function responseHandler(res) {
$.each(res.rows, function(i, row) {
row.state = $.inArray(row.ID, selections) !== -1
})
return res
}
function totalTextFormatter(data) {
return 'Total'
}
function totalNameFormatter(data) {
return data.length
}
function totalPriceFormatter(data) {
var field = this.field
return '$' + data.map(function(row) {
return +row[field].substring(1)
}).reduce(function(sum, i) {
return sum + i
}, 0)
}
function initTable() {
$table.bootstrapTable('destroy').bootstrapTable({
locale: 'de-DE',
columns: [{
field: 'state',
checkbox: true,
rowspan: 1,
align: 'center',
valign: 'middle'
}, {
field: 'id',
title: 'ID',
rowspan: 1,
align: 'center',
valign: 'middle',
sortable: true,
footerFormatter: totalTextFormatter
}, {
field: 'name',
title: 'Kunde',
sortable: true,
align: 'left',
footerFormatter: totalNameFormatter
}, {
field: 'callerid',
title: 'Anrufer',
sortable: true,
align: 'left'
}, {
field: 'datetime_entry_queue',
title: 'DatumZeit',
sortable: true,
align: 'left'
}, {
field: 'duration_wait',
title: 'Warteschleife (sec)',
sortable: true,
align: 'left'
}]
})
$table.on('check.bs.table uncheck.bs.table ' +
'check-all.bs.table uncheck-all.bs.table',
function() {
$remove.prop('disabled', !$table.bootstrapTable('getSelections').length)
//$btnEdit.prop('disabled', !$table.bootstrapTable('getSelections').length)
// save your data, here just save the current page
selections = getIdSelections()
// push or splice the selections if you want to save all data selections
})
$table.on('all.bs.table', function(e, name, args) {
console.log(name, args)
})
}
$(function() {
initTable()
$('#locale').change(initTable)
})
function refreshFunction() {
var data = {
dateVon: $("input[id='dateVon']").val(),
dateBis: $("input[id='dateBis']").val()
};
$.ajax({
method: "post",
url: "verpAnrufData.php",
data: data,
success: function(response) {
/* console.log(data); */
/* params.success({
"rows": data,
"total": data.length
}, null, {}); */
//initTable();
$table.bootstrapTable('refresh')
}
})
}
and this is my MySql php file:
<?php
include "dbConn.php";
$dateVon = $_POST["dateVon"];
$dateBis = $_POST["dateBis"];
$sqltran = mysqli_query($db, "SELECT ce.id,
ce.callerid,
ce.datetime_entry_queue,
ce.duration_wait,
convert(cast(convert(cae.name using latin1) as binary) using utf8) name
FROM call_center.call_entry ce, call_center.campaign_entry cae
WHERE ce.id_campaign = cae.id
AND datetime_entry_queue BETWEEN '$dateVon 00:00:00' AND '$dateBis 23:59:59'
AND status = 'abandonada'
ORDER BY name, datetime_entry_queue ASC;");
$count = mysqli_num_rows($sqltran) ;
$arrVal = array();
$i=1;
while ($rowList = mysqli_fetch_array($sqltran)) {
$name = array(
'id' => $rowList['id'],
'name'=> $rowList['name'],
'callerid'=> $rowList['callerid'],
'datetime_entry_queue'=> $rowList['datetime_entry_queue'],
'duration_wait'=> $rowList['duration_wait'],
);
array_push($arrVal, $name);
$i++;
}
$allData = array(
'total' => $count,
'rows' => $arrVal,
);
echo json_encode($allData);
mysqli_close($db); // close connection
If i harde code the Dates in this file like this:
$dateVon = "2022-01-01";
$dateBis = "2022-12-31";
Then I can see the data, but then I am not able to input another dates and refresh it.
I am desperate I can not make it work, pls help. :)
I have found the answer of my problem, it was in the ajax function and the way I was responding the cell. Thx KIKO Software for the sugesstion.
function refreshFunction() {
$.ajax({
method: "POST",
dataType: "json",
url: "verpAnrufData.php",
data: {
dateVon: $("input[id='dateVon']").val(),
dateBis: $("input[id='dateBis']").val()
},
success: function(response) {
console.log(response);
$table.bootstrapTable('load',{
"rows": response,
"total": response.length
}, null, {});
}
})
};

Datatables: I get 'cannot read property of undefined data' when table is responsive

I have a datatables, which is filled with json data from the db.
As you can see in the last column, there are 2 buttons, one for updating and the other one for deleting the data.
When pressing the button, the value of NumEmpleado(hidden), Nombre, email and Password passes to a form.
It works just fine, buf if I resize my browser enough to kick in the responsiveness layout. Then when I click on the blue button(update), the console says it cannot read the property. I can imagine is because of the responsive layout, but I'm not sure how to deal with it.
This is table code:
<div class="table-responsive col-sm-12">
<table id="dt_cliente" class="table table-bordered table-hover nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>NumEmpleado</th>
<th>Nombre</th>
<th>Correo</th>
<th>TipoCuenta</th>
<th>Operaciones</th>
</tr>
</thead>
</table>
</div>
This is how the table is populated and then adds the update/delete buttons
var listar = function(){
$("#cuadro2").slideUp("slow");
$("#cuadro1").slideDown("slow");
var table = $("#dt_cliente").DataTable({
"destroy":true,
"responsive": true,
"ajax":{
"method":"POST",
"url": "listar.php"
},
"columns":[
{"data": "NumEmpleado"},
{"data": "nombre"},
{"data": "correo"},
{"data": "tipoCuenta"},
{"defaultContent": "<button type='button' class='editar btn btn-primary'><i class='fa fa-pencil-square-o'></i></button> <button type='button' class='eliminar btn btn-danger' data-toggle='modal' data-target='#modalEliminar' ><i class='fa fa-trash-o'></i></button>"}
],
"language": idioma_espanol,
"dom": "Bfrtip",
"buttons": [
{
"text": "<i class='fa fa-refresh'></i>",
"titleAttr": "Recargar Datos",
// "className": "btn btn-sucess",
"action": function(){
listar();
}
},
{
extend: 'excelHtml5',
text: '<i class="fa fa-file-excel-o"></i>',
titleAttr: 'Excel'
},
{
extend: 'csvHtml5',
text: '<i class="fa fa-file-text-o"></i>',
titleAttr: 'CSV'
},
{
extend: 'pdfHtml5',
text: '<i class="fa fa-file-pdf-o"></i>',
titleAttr: 'PDF'
}
]
});
obtener_data_editar("#dt_cliente tbody", table);
}
and this is the function that get the values from the table to place them on a form. (blue update button)
var obtener_data_editar = function(tbody, table) {
$(tbody).on("click", "button.editar", function(){
var data = table.row($(this).parents("tr")).data();
var numEmpleado = $("#numEmpleado").val( data.NumEmpleado),
nombre = $("#nombre").val( data.nombre ),
correo = $("#correo").val(data.correo),
password = $("#password").val(data.password),
opcion = $("#opcion").val("modificar");
$("#cuadro2").slideDown("slow");
$("#cuadro1").slideUp("slow");
});
}
Thank you for your time.
I think the problem is in either of these:-
1)Listener
2)Destroy
3)It is not able find the value of that variable because of some issues.
Kindly check all these and tell me if it solves the issue

Datatable remove row on mobile

I use laravel with datatable to display large data table.
I have a delete button at the end of each row to delete record from my database.
I use ajax and if it's a success I remove the row.
It work well on desktop but it doesn't work on mobile (except if I set computer version).
Here my table :
<table class="datatable table table-striped- table-bordered table-hover table-checkable" id="m_table_1">
<thead>
<tr>
<th>Numéro</th>
<th>Bâtiment</th>
<th>Nature</th>
<th>Options</th>
</tr>
</thead>
</table>
My js to load data :
var table = $('.datatable').DataTable({
responsive: true,
ajax: '{{ route('lots.clientSide') }}',
deferRender: true,
scrollY: '500px',
scrollCollapse: true,
scroller: true,
stateSave: true,
select: true,
language: {
url: "//cdn.datatables.net/plug-ins/1.10.16/i18n/French.json",
select: {
rows: "%d éléments sélectionnés"
}
},
columns: [
{ data: 'id' },
{ data: 'batiment.nom', defaultContent: "----" },
{ data: 'nature' },
{ data: null }
],
columnDefs:[
{targets:-1,title:"Options",width: "10%",orderable:!1,render:function(a,t,e,n){
var slug = e.id;
var url = 'show';
var url_delete = "lots/delete/"+e.id;
return '\n<a href="'+url+'" class="m-portlet__nav-link btn m-btn m-btn--hover-brand m-btn--icon m-btn--icon-only m-btn--pill" title="View">\n'+
'<i class="la la-eye"></i>\n'+
'</a>'+
'<span class="dropdown">\n'+
'<a href="#" class="btn m-btn m-btn--hover-brand m-btn--icon m-btn--icon-only m-btn--pill" data-toggle="dropdown" aria-expanded="true">\n'+
'<i class="la la-ellipsis-h"></i>\n'+
'</a>\n'+
'<div class="dropdown-menu dropdown-menu-left">\n'+
'<a class="dropdown-item" href="#"><i class="la la-edit"></i> Editer</a>\n'+
'<button class="delete dropdown-item" data-href="'+url_delete+'"><i class="la la-trash"></i> Supprimer</button>\n'+
'</div>\n'+
'</span>\n'
}}
]
});
And my code for the remove :
$(document).on('click', '.delete', function(e){
var $this = $(this);
table.row($this.parents('tr')).remove().draw(false);
alert("click");
$.ajax({
type: 'GET',
url: $this.data('href'),
dataType: 'json',
success: function( data ) {
},
error: function(xhr, status, error) {
alert("fail");
}
})
});
I tried with debug tools on computer and I've got nothing on console.
If I use the function on computer, it work. But if I reduce size of the windows, it doesn't work under a certain size.
Is it normal ? Can I do something about it ?
Thank
I manage to avoid this problem by not hidding delete button on mobile.

How to pass route with {id} to Datatable blade. To view specific user details

This is my route
Route::get('/view/{id}', [
'uses' => 'ClientController#view',
'as' => 'view'
]);
This is my Client controller
public function view($id){
$client = Client::where('id',$id)->first();
return view('view',compact('client'));
}
This is my datatable
#extends('layouts.datatables_master')
#section('content')
<table class="table table-bordered" id="clients-table">
<thead>
<tr>
<th>ID</th>
<th>Company Name</th>
<th>Name</th>
<th>Surname</th>
<th>ID Number</th>
<th>Created</th>
<th>Last Updated</th>
<th>Actions</th>
</tr>
</thead>
</table>
#stop
#push('scripts')
<script>
$(function() {
$('#clients-table').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('business.list') !!}',
columns: [
{ data: 'id', name: 'id' },
{ data: 'companyname', name: 'companyname' },
{ data: 'name', name: 'name' },
{ data: 'surname', name: 'surname' },
{ data: 'idnumber', name: 'idnumber' },
{ data: 'created_at', name: 'created_at' },
{ data: 'updated_at', name: 'updated_at' },
{ data: "actions",
"render": function(data, type, row) {
return '<i class="fa fa-search" title="View"></i> <i class="fa fa-pencil" data-toggle="tooltip" data-placement="top" title="Edit"></i> <i class="fa fa-trash" data-toggle="tooltip" data-placement="top" title="Delete"></i>'
;}
}
]
});
});
</script>
#endpush
Problem
My Main issue is passing an ID for all users. If you check my render function on my DataTable I said return route(view,1) where it's 1. I want to pass $id but it says undefined variable. Please help.
You could return the generated route link from your controller like:
return datatables(Client::query())
->addColumn('actions', function ($client) {
return [
'edit_link' => route('view', [$id => $client->id]),
];
})->toJson();
and render in your view as
{
data: "actions",
render: function(data, type, row) {
return
'<a href="' + data.edit_link + '" class="btn btn-xs btn-info">' +
'<i class="fa fa-search" title="View"></i></a>' +
'<a href="#" class="btn btn-xs btn-primary">' +
'<i class="fa fa-pencil" data-toggle="tooltip" data-placement="top" title="Edit"></i>' +
'</a>' +
'<a href="#" class="btn btn-xs btn-danger">' +
'<i class="fa fa-trash" data-toggle="tooltip" data-placement="top" title="Delete"></i>' +
'</a>';
}
}
the value of data should be an 'id', and use url() instead of route() :
{ data: "id",
"render": function(data, type, row) {
return '<a href="{{ url("view") }}/"'+ data +'>View</a>';
}
}
Try like this
return '<i class="fa fa-search" title="View"></i>
You pass the client variable to blade
{{ route('view',$client->id); }}

Datatable jquery + ajax + php can't get data in table (Server-side processing)

I'm using datatable following this example https://datatables.net/examples/data_sources/server_side.html
So my table is:
<table cellpadding="0" cellspacing="0" border="0" class="display" id="tabellaGlossario">
<thead>
<th>
<td>Voce</td>
<td>Sinonimi</td>
<td>Sigla</td>
<td>Macrosettore</td>
<td>Microsettore</td>
<td>Sinonimi</td>
<td>Sigla</td>
<td>Macrosettore</td>
<td>Microsettore</td>
</th>
</thead>
<tfoot>
<th>
<td>Voce</td>
<td>Sinonimi</td>
<td>Sigla</td>
<td>Macrosettore</td>
<td>Microsettore</td>
<td>Sinonimi</td>
<td>Sigla</td>
<td>Macrosettore</td>
<td>Microsettore</td>
</th>
</tfoot>
</table>
My js:
oTable = $('#tabellaGlossario').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"sDom": '<""f>t<"F"lp>',
"processing": true,
"serverSide": true,
"ajax": "Modules/Glossario/View/Glossario.Table.View.php?lingua_select=2",
});
My ajax returned:
{
"draw": 1,
"recordsTotal": 1,
"recordsFiltered": 1,
"data": [
[
"1",
"2",
"1",
"1",
"1",
"Parola italiana",
"Sinonimo italiano",
"Sigla ita",
"Note ita"
]
]
}
My problem is that i always get "No data available in table" as table results. But as you can see ajax has some results (1 in this example).
It seems my code is the same as the one in official example.
Can't understand why data are not showed in table (and i get no error in browser console).
Are you using some dynamic loading or any kind of routing?
For example angularjs ngroute or some framework's.
In that case it can't work (not as you're doing). You can follow some guide like this or example like this http://jsfiddle.net/qu4a7j24/3/
<div ng-app='testTableApp'>
<div class="container">
<div ng-controller="mainTable">
<form action="" method="POST" class="form-horizontal" role="form">
<div class="form-group">
<legend>Filters</legend>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input type="text" value="0" ng-change='reloadData()' ng-model="start">
<input type="text" value="50" ng-change='reloadData()' ng-model="end">
</div>
</div>
</form>
<table datatable="" dt-options="dtOptions" dt-columns="dtColumns" class="table table-striped table-bordered"></table>
</div>
</div>
</div>
var testTableApp = angular.module( 'testTableApp', ['ngRoute', 'ngResource', 'datatables', 'datatables.tabletools', 'datatables.bootstrap', 'datatables.fixedheader'] );
console.log( testTableApp );
testTableApp.controller("mainTable",
[ '$scope', 'DTOptionsBuilder', 'DTColumnBuilder',
function ( $scope, DTOptionsBuilder, DTColumnBuilder){
$scope.dataSource = "http://dt.ishraf.com/ajax.php";
$scope.start = 0;
$scope.end = 5000;
$scope.getDataSource = function(obj,prefix){
var src = $scope.dataSource;
var str = [];
for(var p in obj) {
if (obj.hasOwnProperty(p)) {
var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
str.push(typeof v == "object" ?
serialize(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
return src + "?" + str.join("&");
}
var dsParams = {
start : $scope.start,
end : $scope.end
}
$scope.dsString = $scope.getDataSource( dsParams );
$scope.buildTable = function(){
return DTOptionsBuilder
.newOptions()
.withOption('ajax', {
// Either you specify the AjaxDataProp here
dataSrc: 'data',
url: $scope.dsString,
type: 'POST'
}).
withOption( 'lengthMenu', [
[10, 20, 50, 100, 150, 300, 500],
[10, 20, 50, 100, 150, 300, 500]
])
.withTableTools('bower_components/datatables-tabletools/swf/copy_csv_xls_pdf.swf')
.withTableToolsButtons([
{
"sExtends": "copy",
"sButtonText": "<i class='fa fa-copy'></i> | Copy",
"fnInit": function (nButton, oConfig) {
$(nButton).addClass('btn btn-success');
}
},
{
"sExtends": "print",
"sButtonText": "<i class='fa fa-print'></i> | Print",
"fnInit": function (nButton, oConfig) {
$(nButton).addClass('btn btn-danger');
}
},
{
"sExtends": "csv",
"sButtonText": "<i class='fa fa-file-o'></i> | CSV",
"fnInit": function (nButton, oConfig) {
$(nButton).addClass('btn btn-primary');
}
},
{
"sExtends": "pdf",
"sButtonText": "<i class='fa fa-file-pdf-o'></i> | PDF",
"fnInit": function (nButton, oConfig) {
$(nButton).addClass('btn btn-warning');
}
}
])
.withFixedHeader({
bottom: true
})
.withDOM('<"clear"><"#top.hidden-print"<".row"<".col-md-6"i><".col-md-6"f>><".row"<".col-md-6"l><".col-md-6"p>><"clear">T>rt')
;
}
$scope.dtOptions = $scope.buildTable();
$scope.buildColumns = function(){
return [
DTColumnBuilder.newColumn('id').withTitle('ID'),
DTColumnBuilder.newColumn('firstName').withTitle('First name'),
DTColumnBuilder.newColumn('lastName').withTitle('Last name'),
DTColumnBuilder.newColumn('city').withTitle('city'),
DTColumnBuilder.newColumn('state').withTitle('state'),
DTColumnBuilder.newColumn('zip').withTitle('zip'),
DTColumnBuilder.newColumn('country').withTitle('country'),
DTColumnBuilder.newColumn('phone').withTitle('phone'),
DTColumnBuilder.newColumn('email').withTitle('email')
];
}
$scope.dtColumns = $scope.buildColumns();
$scope.reloadData = reloadData;
$scope.dtInstance = {};
function reloadData() {
var resetPaging = false;
$scope.dtInstance.reloadData(callback, resetPaging);
}
function callback(json) {
console.log(json);
}
}
]);
or just dynamic create the table (.load jquery can be useful)

Categories