how to sum column in datatables (i'm using codeigniter) - javascript

I'm using codeigniter and datatables for my view data. But i'm stuck how to get sum column. I have 2 fields named barang_qty, and barang_qty_toko. I need to sum this and display on datatables.
This is my Controller :
function ajax_tableBarang(){
if(!$this->input->is_ajax_request()) {
exit('No direct script access allowed');
}else{
$this->load->library('datatables_ssp');
$table = 'barang';
$primaryKey = 'barang_id';
$columns = array(
array( 'db' => 'barang_id', 'dt' => 'DT_RowID' ),
array( 'db' => 'barang_kode', 'dt' => 'barang_kode' ),
array( 'db' => 'barang_type', 'dt' => 'barang_type' ),
array( 'db' => 'barang_size', 'dt' => 'barang_size' ),
array( 'db' => 'barang_qty', 'dt' => 'barang_qty'), //I want this field result from summation of barang_qty and barang_qty_toko
array( 'db' => 'barang_harga', 'dt' => 'barang_harga' ),
array( 'db' => 'barang_klasifikasi', 'dt' => 'barang_klasifikasi'),
);
$sql_details = array(
'user' => 'user',
'pass' => 'passwd',
'db' => 'pjtomato',
'host' => 'localhost'
);
$where = "";
echo json_encode(Datatables_ssp::simple($_GET, $sql_details, $table, $primaryKey, $columns, $where));
}
}
And this is my view :
<div role="tabpanel" class="tab-pane fade in active" id="tab-all">
<table id="tableAllItem" class="table table-bordered table-striped table-hover" cellspacing="0" width="100%">
<thead>
<tr class="info">
<th>#</th>
<th>Kode</th>
<th>Jenis</th>
<th>Ukuran</th>
<th>Quantity</th> // Total of quantity (summation of barang_qty + barang_qty_toko) will display here
<th>Harga</th>
<th>Klasifikasi</th>
</tr>
</thead>
</table>
And this is the javascript for datatables:
<script type="text/javascript">
$.fn.dataTableExt.oApi.fnPagingInfo = function (oSettings){
return{
"iStart": oSettings._iDisplayStart,
"iEnd": oSettings.fnDisplayEnd(),
"iLength": oSettings._iDisplayLength,
"iTotal": oSettings.fnRecordsTotal(),
"iFilteredTotal": oSettings.fnRecordsDisplay(),
"iPage": Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength),
"iTotalPages": Math.ceil(oSettings.fnRecordsDisplay() / oSettings._iDisplayLength)
};
};
var t = $('#tableAllItem').DataTable({
"processing": true,
"serverSide": true,
"ajax": "<?php echo site_url('cAdminPage/ajax_tableBarang'); ?>",
"columns": [
{ "data": "barang_kode" },
{ "data": "barang_kode" },
{ "data": "barang_type" },
{ "data": "barang_size" },
{ "data": "barang_qty"},
{ "data": "barang_harga" },
{ "data": "barang_klasifikasi" },
],
"order": [[1, 'asc']],
"rowCallback": function (row, data, iDisplayIndex){
var info = this.fnPagingInfo();
var page = info.iPage;
var length = info.iLength;
var index = page * length + (iDisplayIndex + 1);
$('td:eq(0)', row).html(index);
}
});
Please advice,
Thanks

Related

How to change data in DataTable using select option

Front datatable
this is front end of datatable
I want to change datatable data from select option. first time it's working after change to other category display error.
DataTables warning: table id=tblviewstock - Cannot reinitialise DataTable
<table id="tblviewstock" class="table table-striped " >
<thead>
<tr>
<th>Batch ID</th>
<th>Product ID</th>
<th>selling price</th>
<th>Quantity</th>
<th>Receive Date</th>
</tr>
</thead>
<tbody id="stockBody" style="font-size: 13px">
</tbody>
</table>
javascript
$("#stock_cat").change(function () {
var cat_id = $(this).val();
var dataTable = $("#tblviewstock").DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "lib/mod_stock.php?type=viewStock&catid="+cat_id,
"type": "POST"
},
"columns": [
{"data": "0"},
{"data": "1"},
{"data": "2"},
{"data": "3"},
{"data": "4"},
]
});
});
mod_view.php - function view_stock()
this file is mod-view.php
function viewStock(){
$catid = $_GET['catid'];
$table ='tbl_products';
$primaryKey ='prod_id';
$where = "cat_id='$catid'";
$columns = array(
array( 'db' => 'prod_id', 'dt'=> 0),
array( 'db' => 'prod_img', 'dt'=> 1),
array( 'db' => 'prod_name', 'dt'=> 2),
array( 'db' => 'prod_modal', 'dt'=> 3),
array( 'db' => 'prod_color', 'dt'=> 4),
);
require_once('config.php');
$host = Config::$host ;
$user = Config::$db_uname ;
$pass = Config::$db_upass ;
$db = Config::$db_name ;
$sql_details = array(
'user' => $user,
'pass' => $pass,
'db' => $db,
'host' => $host
);
require('ssp.class.php');
echo json_encode(
SSP::complex($_POST, $sql_details, $table, $primaryKey, $columns,null,$where )
);
}
The Datatables cannot be reinisialised. (i.e the options cannot be set twice for the same table). You can try and destroy the table and recreate it once a new category is selected. Perhaps try:
var dataTable;
var i = 0;
$("#stock_cat").change(function () {
if(++i > 1) dataTable.destroy();
var cat_id = $(this).val();
dataTable = $('#tblviewstock').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "lib/mod_stock.php?type=viewStock&catid="+cat_id,
"type": "POST"
},
"columns": [
{"data": "0"},
{"data": "1"},
{"data": "2"},
{"data": "3"},
{"data": "4"},
]
});
});

Datatables (Row Details): Uncaught TypeError: Cannot read property 'style' of undefined

im trying to implement the datatables row details
this is my table that has an id of "user_datas"
<table id="user_datas" class="table table-bordered table-striped" width="100%">
<thead>
<tr>
<th>NAME</th>
<th>SEX</th>
<th>BIRTHDATE</th>
<th>AGE</th>
</tr>
</thead>
</table>
this is the code that comes from the datatable documentation which im trying to implement
function format ( d ) {
return 'Name: '+d.name+'<br>'+
'Gender: '+d.sex+'<br>'+
'The child row can contain any data you wish, including links, images, inner tables etc.';
}
$(document).ready(function() {
var dataTable = $('#user_datas').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"../controller/fetch_senior_citizen.php",
type:"POST"
},
"columns": [
{
"class": "details-control",
"orderable": false,
"data": null,
"defaultContent": ""
},
{ "data": "name" },
{ "data": "sex" },
{ "data": "birthdate" },
{ "data": "age" }
],
"order": [[1, 'asc']]
});
// Array to track the ids of the details displayed rows
var detailRows = [];
$('#user_datas tbody').on( 'click', 'tr td.details-control', function () {
var tr = $(this).closest('tr');
var row = dataTable.row( tr );
var idx = $.inArray( tr.attr('id'), detailRows );
if ( row.child.isShown() ) {
tr.removeClass( 'details' );
row.child.hide();
// Remove from the 'open' array
detailRows.splice( idx, 1 );
}
else {
tr.addClass( 'details' );
row.child( format( row.data() ) ).show();
// Add to the 'open' array
if ( idx === -1 ) {
detailRows.push( tr.attr('id') );
}
}
} );
// On each draw, loop over the `detailRows` array and show any child rows
dataTable.on( 'draw', function () {
$.each( detailRows, function ( i, id ) {
$('#'+id+' td.details-control').trigger( 'click' );
} );
} );
});
and this is some of my code from fetch_senior_citizen.php
foreach($result as $row)
{
$name = clean($row["f_name"])." ".clean($row["m_name"])." ".clean($row["l_name"]);
$sub_array = array();
$sub_array["id"] = $row['id'];
$sub_array["name"] = $name;
$sub_array["sex"] = strtoupper($row["sex"]);
$sub_array["birthdate"] = $row["birthdate"];
$sub_array["age"] = $row["age"];
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rowsz,
"recordsFiltered" => get_total_all_records4(),
"data" => $data
);
echo json_encode($output, JSON_PRETTY_PRINT);
the error that im currently facing is Uncaught TypeError: Cannot read property 'style' of undefined but if i remove this code
{
"class": "details-control",
"orderable": false,
"data": null,
"defaultContent": ""
}
Everythings work fine. But my table doesnt have row details
Problem solved! i just forgot to put an empty th on thead

How to do data tables in codeigniter?

I am fetching records from database and converting data into json array. I am getting json response correctly. but table shows no entry in my view.. please see once . Thanks.
my controller
function test() {
$list = $this->get_data_model->get_apartment_details();
$data = array();
$no = $_POST['start'];
foreach ($list as $apartments) {
$no++;
$row = array();
$row[] = $no;
$row[] = $apartments->a_id;
$row[] = $apartments->a_name;
$data[] = $row;
}
$output = array(
"draw" => 5,
"recordsTotal" => 2,
"recordsFiltered" => 1,
"data" => $data
);
echo json_encode($output);//
}
my view
<section class="tab-pane fade in active" id="newPanel">
<table style='width:100%'' class='table' id='example'>
<thead>
<tr>
<th> ID </th>
<th> Name </th>
<th> Activate </th>
<th> Edit </th>
</tr>
</thead>
</table>
</section>
my ajax call
$('#example').DataTable( {
"processing" : true,
"serverSide" : true,
"ajax" : {
"type" : "POST",
"url": "<?php echo base_url("apartments/test");?>",
"dataSrc" : ""
},
"columns": [
{ "data": "a_id"},
{ "data": "a_name" }
],
"dom": 'Bfrtip',
"buttons": [
{
"extend": 'copyHtml5',
"exportOptions": {
"columns": ':contains("Office")'
}
},
'excelHtml5',
'csvHtml5',
'pdfHtml5'
]
} );
} );
Your Table ID attribute and your ajax call id attribute is different. hope below code will help you.
$('#newPanel').DataTable( {
"processing" : true,
"serverSide" : true,
"ajax" : {
"type" : "POST",
"url": "<?php echo base_url("apartments/test");?>",
"dataSrc" : ""
},
"columns": [
{ "data": "a_id"},
{ "data": "a_name" }
],
"dom": 'Bfrtip',
"buttons": [
{
"extend": 'copyHtml5',
"exportOptions": {
"columns": ':contains("Office")'
}
},
'excelHtml5',
'csvHtml5',
'pdfHtml5'
]
} );
} );

Datatables Date and Time Input

I'm trying to use the date and time input in datatables used here https://editor.datatables.net/examples/dates/datetime.html
This is what I've tried
<script type="text/javascript" src="<?php echo base_url('assets/js/jquery-3.1.1.min.js');?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/js/materialize.min.js');?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/js/jquery.dataTables.js');?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/js/moment.js');?>"></script>
<script type="text/javascript">
//use a global for the submit and return data rendering in the examples
var editor;
$(document).ready(function() {
editor = new $.fn.dataTable.Editor( {
table: '#receivablesLogs',
fields: [ {
label: 'Date:',
name: 'date'
type: 'datetime',
def: function () { return new Date(); },
format: 'MM-DD-YYYY',
fieldInfo: 'US style m-d-y date input'
},
{
label: 'Invoice Number:',
name: 'invoice_number'
},
{
label: 'Customer Name:',
name:'customer_name'
},
{
label: 'Total Amount:',
name: 'total_amount'
},
{
label: 'Due Date:',
name: 'due_date'
type: 'datetime',
def: function () { return new Date(); },
format: 'MM-DD-YYYY',
fieldInfo: 'US style m-d-y date input'
}
]
} );
$('#receivablesLogs').DataTable( {
dom: 'Bfrtip',
columns: [
{data: 'date'},
{data: 'invoice_number'},
{data: 'customer_name'},
{data: 'total_amount'},
{data: 'due_date'}
],
select: true,
order: [[ 0, 'asc' ]],
bFilter: false,
bLengthChange: false,
paging: false,
bFiler: false
});
});
</script>
and here is my table
<table id="receivables" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Date</th>
<th>Invoice Number</th>
<th>Customer Name</th>
<th>Total Amount</th>
<th>Due Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>03/31/2014</td>
<td>12456</td>
<td>Customer One</td>
<td>160,000.00</td>
<td>04/25/2015</td>
</tr>
<tr>
<td>02/28/2015</td>
<td>12456</td>
<td>Customer One</td>
<td>160,000.00</td>
<td>04/25/2015</td>
</tr>
</tbody>
</table>
But I don't know where I went wrong. I imported the correct js files but it doesn't display correctly. This is the output that I'm getting
Also I don't get what this line ajax: '../php/datetime.php' is for. I don't see what is the datetime.php that the documentation is referring to.
This is my first time trying datatables so I don't know where I did wrong. I already tried the basic creation of datatables and it worked but I had a problem when I tried to incorporate the date and time input in my codes.
UPDATE 1: There exists a server side script like this in the documentation
<?php
/*
* Example PHP implementation used for date time examples
*/
// DataTables PHP library
include( "../../php/DataTables.php" );
// Alias Editor classes so they are easy to use
use
DataTables\Editor,
DataTables\Editor\Field,
DataTables\Editor\Format,
DataTables\Editor\Mjoin,
DataTables\Editor\Options,
DataTables\Editor\Upload,
DataTables\Editor\Validate;
// Build our Editor instance and process the data coming from _POST
Editor::inst( $db, 'users' )
->fields(
Field::inst( 'first_name' ),
Field::inst( 'last_name' ),
Field::inst( 'updated_date' )
->validator( 'Validate::dateFormat', array(
'empty' => false,
'format' => 'm-d-Y g:i A'
) )
->getFormatter( 'Format::datetime', array(
'from' => 'Y-m-d H:i:s',
'to' => 'm-d-Y g:i A'
) )
->setFormatter( 'Format::datetime', array(
'from' => 'm-d-Y g:i A',
'to' => 'Y-m-d H:i:s'
) ),
Field::inst( 'registered_date' )
->validator( 'Validate::dateFormat', array(
'format' => 'j M Y H:i'
) )
->getFormatter( 'Format::datetime', array(
'from' => 'Y-m-d H:i:s',
'to' => 'j M Y H:i'
) )
->setFormatter( 'Format::datetime', array(
'from' => 'j M Y H:i',
'to' => 'Y-m-d H:i:s'
) )
)
->process( $_POST )
->json();
Where should I put this?
I pull this code snippet from the site you provided a link for:
$('#example').DataTable( {
dom: 'Bfrtip',
ajax: '../php/datetime.php',
columns: [
{ data: 'first_name' },
{ data: 'last_name' },
{ data: 'updated_date' },
{ data: 'registered_date' }
],
select: true,
buttons: [
{ extend: 'create', editor: editor },
{ extend: 'edit', editor: editor },
{ extend: 'remove', editor: editor }
]
} );
Ajax is a set of techniques to load data dynamically, behind the scenes.
Some information here: https://developer.mozilla.org/en-US/docs/AJAX
The link: "../php/datetime.php" is given as an example.
datetime.php is a file you would have to actually make in php.
In this case, datetime.php runs on the back-end, and probably queries some database.

Data tables server-side formating links

I have a table with tones of records and I need some links inside the table, so the problem is about formatting...
The first row is a link of the name of the patient to his single page and the last row is a collection of links for edit and delete the patient.
The problem:
Now with this code in the first row don't appear the name (row[1]),
appear the surnames (row[2]) but the link is ok (row[0])
In the last row both links are working good, but thickybox is not
working, the link is opened in a new page.
Can somebody help me with that? thank's in advance!!! :)
Server-side processing script:
$columns = array(
array(
'db' => 'id',
'dt' => 0,
'formatter' => function( $d, $row ) {
$links=''.$row[1].'';
return $links;
}),
array( 'db' => 'apellidos', 'dt' => 1 ),
array( 'db' => 'tel_mov', 'dt' => 2 ),
array( 'db' => 'terapeuta', 'dt' => 3 ),
array(
'db' => 'id',
'dt' => 4,
'formatter' => function( $d, $row ) {
$links2='<img src="ima/edit.png" /> | <img src="ima/close.png" />';
return $links2;
}),
);
Javascript:
$(document).ready(function() {
$('#tablet').DataTable({
"language": {
"url": "https://cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Spanish.json"},
"scrollY": "400px",
"scrollCollapse": true,
"processing": true,
"serverSide": true,
"ajax": "load.php"
});
} );
I got it ;)
For the links names problems:
Just add first column of the table a id data and if you don't need it hide it with options in the javascript ("bVisible": false)
So now the $row[0] is always the id and the $row[1] the name...
For the thickbox problem:
Just add "aoColumns" whith the options an after "fnDrawCallback"
"aoColumns": [
{ "sTitle": "id","bVisible": false},
{ "sTitle": "Nombre" },
{ "sTitle": "Apellidos" },
{ "sTitle": "Móbil","bSortable": false },
{ "sTitle": "Fijo","bSortable": false },
{ "sTitle": "Terapeuta","bSortable": false },
{ "sTitle": "Edición","bSortable": false,"bSearchable": false }],
"fnDrawCallback": function() {
tb_init('a.thickbox');
}
I don't know if is the best way but is working for me ;)

Categories