mRenderProp not returning the button - php

I am building a CRUD application which runs on Data-tables server-side processing, I managed to generate the table dynamically but when I try to create a click-able button for viewing more information, it fails and only shows the unique identifier.
Please advise what am I not doing correctly at the mRenderProp?
Below is my script that generates the data-table :
<script type="text/javascript">
$(document).ready(function () {
Draw();
function Draw() {
$('#example_ta').dataTable({
"bJQueryUI": true,
"bautoWidth": false,
"aoColumns": [
{"sTitle": "Delivery Date", "mDataProp": "delivery_date"},
{"sTitle": "Delivery No.", "mDataProp": "delivery_no"},
{"sTitle": "Unit Code", "mDataProp": "unit_code"},
{"sTitle": "Driver Code.", "mDataProp": "driver_code"},
{"sTitle": "Zone Name.", "mDataProp": "zone_name"},
{"sTitle": "Zone Rate", "mDataProp": "zone_rate"},
{"sTitle": "Tonnage", "mDataProp": "tonnage"},
{"sTitle": "Standard Tonne", "mDataProp": "standard_tonne"},
{"sTitle": "View", "mDataProp": "delivery_id",
"mRenderProp": function (data, type, full) {
return '<button class="show-data btn btn-small btn-primary" id = ' + data + ' >View</button>';
}
},
],
"bDeferRender": true,
"bProcessing": true,
"bDestroy": true,
"bLengthChange": true,
"iDisplayLength": 10,
"sAjaxDataProp": "",
"sAjaxSource": '<?php echo site_url() . "admin_profile/getDeliveries/"; ?>',
"aaSorting": [[3, "asc"]]
});
}
});
</script>
<table class="example_ta" id="example_ta">
<thead>
<tr>
</tr>
</thead>
<tbody>
<tr></tr>
</tbody>
</table>

It's just mRender not mRenderProp - see docs
{"sTitle": "View", "mDataProp": "delivery_id",
"mRender": function (data, type, full) {
return '<button class="show-data btn btn-small btn-primary" id = ' + data + ' >View</button>';
}

Related

Laravel 5.5 - Pass MySQL query to Javascript function/DataTables

I'd like to pass a SQL query to a Javascript function, found in my view, which will populate a HTML table using the DataTables API. I'm having trouble converting the object array into plain JSON. How would I go about doing so?
[web.php]
Route::get('/admin', function () {
$users = DB::connection('mysql')->select('SELECT * FROM users');
return view('admin', compact('users'));
});
[admin.blade.php] (HTML)
<div class="row">
<div class="col-lg-6">
<div class="card mb-3">
<div class="card-header"><i class="fa fa-user"></i> Users</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered table-striped table-compact" width="100%" id="userTable" cellspacing="0"></table>
</div>
</div>
</div>
</div>
</div>
[admin.blade.php] (Javascript)
<script type="text/javascript">
$(document).ready(function() {
$('#userTable').DataTable( {
"scrollX": true,
"scrollY": '55vh',
"scrollCollapse": true,
"paging": false,
dom: 'ft',
"aaData": "{{ $users }}",
"aoColumns": [
{ "sTitle": "Name", "mData": "name" },
{ "sTitle": "Email", "mData": "email" },
]
} );
} );
</script>
[Example JSON object/array returned from database]
array:1 [
0 => {#195
+"id": 1
+"name": "Josh_W"
+"email": "user#email.com"
+"group": "Admin"
+"level": 5
+"password": "PASSWORD"
+"remember_token": null
+"created_at": "2017-10-12 14:42:38"
+"updated_at": "2017-10-12 14:42:38"
}
]
The select() method returns an array. You need to collect() the array and then call toJson():
<script type="text/javascript">
$(document).ready(function() {
$('#userTable').DataTable( {
"scrollX": true,
"scrollY": '55vh',
"scrollCollapse": true,
"paging": false,
dom: 'ft',
"aaData": {!! collect($users)->toJson() !!},
"aoColumns": [
{ "sTitle": "Name", "mData": "name" },
{ "sTitle": "Email", "mData": "email" },
]
} );
} );
</script>
To avoid escaping your JSON use the {!! !!} syntax.
See the Laravel documentation on collections and displaying data on views for reference.

Datatable export option is not working

Anyone can please help me why data table export option not working on the below-given link.
http://ec2-52-66-146-251.ap-south-1.compute.amazonaws.com/Purvi/index.php/Ledger/ledger_view/18
jQuery:
var table = $('#example').DataTable({
"ordering": false,
buttons: [{
extend: "print",
className: "btn dark btn-outline"
}, {
extend: "copy",
className: "btn red btn-outline"
}, {
extend: "pdf",
className: "btn green btn-outline"
}, {
extend: "excel",
className: "btn yellow btn-outline "
}, {
extend: "csv",
className: "btn purple btn-outline "
}, {
extend: "colvis",
className: "btn dark btn-outline",
text: "Columns"
}],
});
Please help me why the data table export option is not working on given link.
Replace your above code to this and try :
$('#example').DataTable({
"ordering": false,
buttons: [{
extend: "print",
className: "btn dark btn-outline"
}, {
extend: "copy",
className: "btn red btn-outline"
}, {
extend: "pdf",
className: "btn green btn-outline"
}, {
extend: "excel",
className: "btn yellow btn-outline "
}, {
extend: "csv",
className: "btn purple btn-outline "
}, {
extend: "colvis",
className: "btn dark btn-outline",
text: "Columns"
}],
});
Have you included this library files?
- https://cdn.datatables.net/r/dt/jq-2.1.4,jszip-2.5.0,pdfmake-0.1.18,dt-1.10.9,af-2.0.0,b-1.0.3,b-colvis-1.0.3,b-html5-1.0.3,b-print-1.0.3,se-1.0.1/datatables.min.css"/>
You already added required files?
- https://cdn.datatables.net/r/dt/jq-2.1.4,jszip-2.5.0,pdfmake-0.1.18,dt-1.10.9,af-2.0.0,b-1.0.3,b-colvis-1.0.3,b-html5-1.0.3,b-print-1.0.3,se-1.0.1/datatables.min.js
You should also check this usage to include.
"dom": 'lBfrtip',

How to filter a numeric status that appears as text in kendo-ui?

I'm using kendo-ui to render a grid.
I need to filter a table which has a "status" field. In the database this field is a numeric, but it represents "active" and "inactive".
When I filter the column by "0" or "1" it works correctly, but I need to filter using the terms "active" and "inactive".
This is my code:
<script type="text/javascript">
$(document).ready(function(e) {
//carrega o grid da página
kendo.ui.FilterCell.fn.options.template = function(e){
e.element.kendoAutoComplete({
serverFiltering: false,
valuePrimitive: true,
noDataTemplate: ''
});
}
var dataSource = new kendo.data.DataSource({
//data: data,
transport: {
read:{
url: '{{url('franquias/franquias_get')}}',
dataType: 'json', //not needed jQuery figures it out, shown to be verbose
type: 'GET' //defined but, this is the default
}
},
serverPaging: true,
serverFiltering: true,
serverSorting: true,
pageSize: 10,
schema: {
model: {
id: "id_franquia",
fields: {
id_franquia: { type: "number" },
nm_franquia: { type: "string" },
}
},
data: "data",
total:"total"
},
pageable: {
refresh: true,
pageSizes: true
},
});
var grid= $("#grid").kendoGrid({
dataSource: dataSource,
pageable:true,
scrollable: false,
sortable: true,
navigatable: true,
resizable: true,
columnMenu: {
filterable: false,
sortable: false
},
filterable: {
mode: "row"
},
columns: [
{ field: "id_franquia", title: 'Id', width: 150, headerTemplate: 'Id <span class="k-icon k-i-kpi"></span>'},
{ field: "nm_franquia", title: 'Nome', headerTemplate: 'Nome <span class="k-icon k-i-kpi"></span>'},
{ field: "nm_franquia_abrev", title: 'Abreviação', headerTemplate: 'Abreviação <span class="k-icon k-i-kpi"></span>'},
{ field: "nu_status", title: 'Status', headerTemplate: 'Status <span class="k-icon k-i-kpi"></span>', values: [ { text: "Ativo", value: 1 }, { text: "Inativo", value: 0 }]},
{ field: "created_at", title: 'Data Cadastro', headerTemplate: 'Data Cadastro <span class="k-icon k-i-kpi"></span>', hidden:true },
{ field: "action", title:"Ação", width: 125, filterable:false,menu:false, template:"<form method='POST' action='/franquias/#=id#' accept-charset='UTF-8'><input name=\"_method\" type=\"hidden\" value=\"DELETE\"><input type=\"hidden\" name=\"_token\" value=\"{{ csrf_token() }}\"> <a class=\"btn btn-default \" href=\"/franquias/#=id#/edit\"><i class=\"fa fa-pencil\"></i></a><button type=\"submit\" class=\"btn btn-default\" onclick=\"return confirm('Tem certeza que deseja deletar?')\"><i class=\"fa fa-trash\"></i></button> </div></form>"}
]
}).data("kendoGrid");
grid.thead.find(".k-header-column-menu").hide();
grid.thead.find("[data-field=action]>.k-header-column-menu").show();
});
</script>
Please try with the below code snippet.
<!DOCTYPE html>
<html>
<head>
<base href="http://demos.telerik.com/kendo-ui/grid/local-data-binding">
<style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.2.504/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.2.504/styles/kendo.material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.2.504/styles/kendo.material.mobile.min.css" />
<script src="https://kendo.cdn.telerik.com/2017.2.504/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.2.504/js/kendo.all.min.js"></script>
</head>
<body>
<script>
var products = [{
ProductID : 1,
ProductName : "Chai",
SupplierID : 1,
CategoryID : 1,
QuantityPerUnit : "10 boxes x 20 bags",
UnitPrice : 18.0000,
UnitsInStock : 39,
UnitsOnOrder : 0,
ReorderLevel : 10,
Discontinued : 0,
}, {
ProductID : 2,
ProductName : "Chang",
SupplierID : 1,
CategoryID : 1,
QuantityPerUnit : "24 - 12 oz bottles",
UnitPrice : 19.0000,
UnitsInStock : 17,
UnitsOnOrder : 40,
ReorderLevel : 25,
Discontinued : 0,
}, {
ProductID : 3,
ProductName : "Aniseed Syrup",
SupplierID : 1,
CategoryID : 2,
QuantityPerUnit : "12 - 550 ml bottles",
UnitPrice : 10.0000,
UnitsInStock : 13,
UnitsOnOrder : 70,
ReorderLevel : 25,
Discontinued : 0,
}, {
ProductID : 4,
ProductName : "Chef Anton's Cajun Seasoning",
SupplierID : 2,
CategoryID : 2,
QuantityPerUnit : "48 - 6 oz jars",
UnitPrice : 22.0000,
UnitsInStock : 53,
UnitsOnOrder : 0,
ReorderLevel : 0,
Discontinued : 1,
}];</script>
<div id="example">
<div id="grid"></div>
<script>
$(document).ready(function() {
$("#grid").kendoGrid({
dataSource: {
data: products,
schema: {
model: {
fields: {
ProductName: { type: "string" },
UnitPrice: { type: "number" },
UnitsInStock: { type: "number" },
Discontinued: { type: "string" }
}
}
},
pageSize: 20
},
height: 550,
scrollable: true,
sortable: true,
filterable: true,
pageable: {
input: true,
numeric: false
},
columns: [
"ProductName",
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: "130px" },
{ field: "UnitsInStock", title: "Units In Stock", width: "130px" },
{ field: "Discontinued", width: "130px",
headerTemplate: 'Status <span class="k-icon k-i-kpi"></span>', values: [ { text: "active", value: 1 }, { text: "inactive", value: 0 }]}
]
});
});
</script>
</div>
</body>
</html>
Demo
Let me know if any concern.

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)

DataTables - display a button in a cell of every row

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
});

Categories