Data tables server-side formating links - javascript

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

Related

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.

how to build this json in php

im using php to send a push but my json object isent getting the way i want...
i need my json to be like this :
{
"to": ["xxx"],
"data": {
"title": "dw",
"body": "dw",
"actions": [
{ "icon": "emailGuests", "title": "Candidatar-me", "callback": "app.emailGuests", "foreground": true},
]
}
}
but im getting this instead :
{
"to": "xxx",
"data": {
"title": "dw",
"body": "dw",
"actions": {
"icon": "send.ico",
"title": "EMAIL GUESTS",
"callback": "app.callbackName",
"foreground": true
}
}
}
i am building my json like this :
$fields = array ( 'to' => $row1['fcm_registered_id'] ,
'priority' => "high",
'data' => array("title" =>$titlepost,
"body"=> $msg,
"actions" => array('icon' => 'send.ico',
'title' => 'EMAIL GUESTS',
'callback' => 'app.callbackName',
'foreground' => true
)
),
);
Remember that json_encodeconverts non-numeric indexed arrays to objects. There is why you gets objects instead of array of objects. It's enough to wrap this array by another array. Here is fixed code:
$fields = array (
'to' => array( $row1['fcm_registered_id'] ),
'data' => array(
"title" =>$titlepost,
"body"=> $msg,
"actions" => array(
array(
'icon' => 'send.ico',
'title' => 'EMAIL GUESTS',
'callback' => 'app.callbackName',
'foreground' => true
)
)
)
);
And here is working example: http://phpio.net/s/1n0e
Little note: try to use new array syntax: [] than old array()

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

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

Datatables Simple Join Query

I am putting together a simple join query using Datatables Editor however am getting errors which I don't understand. My code is below:
HTML
<!-- Actions -->
<div id="divActions" class="tab-pane fade">
<ul class="nav nav-list">
<!-- Actions Tab Header -->
<legend id="lgdActions">Actions</legend>
<table id="tblActions" class="display" cellspacing="0" width="100%"></table>
</ul>
</div>
Javascript
Actions Datagrid
$('#tblActions').DataTable({
dom: "Tfrtip",
lengthChange: false,
bAutoWidth: false,
jQueryUI: true,
bProcessing: true,
bServerSide: true,
ajax: {
url: "dataGridQuery.php",
data: { "gridNumber": 2 },
type: 'POST'
},
columns: [
{ title: "Action ID", data: "tblActions.actionID", width: "10%" },
{ title: "Time", data: "tblActions.actionTime" },
{ title: "Action Taken", data: "tblActions.actionTaken" },
{ title: "User", data: "tblUsers.userID" }
]
tableTools: {
sRowSelect: "os",
aButtons: [
{ sExtends: "editor_create", editor: editor1 },
{ sExtends: "editor_edit", editor: editor1 },
{ sExtends: "editor_remove", editor: editor1 }
]
}
});
PHP
// Obtain Action Grid
if(isset($_GET['gridNumber']) && $_GET['gridNumber']==2){
//
$data = Editor::inst( $db, 'tblActions' )
->field(
Field::inst( 'tblActions.actionID' ),
Field::inst( 'tblActions.actionTime' ),
Field::inst( 'tblActions.actionTaken' ),
Field::inst( 'tblActions.actionUserID' ),
Field::inst( 'tblUsers.userID' )
)
->leftJoin( 'tblUsers', 'tblUsers.userID', '=', 'tblActions.actionUserID' )
->process($_POST)
->data();
//
if ( ! isset($_POST['action']) ) {
// Get a list of sites for the `select` list
$data['tblUsers'] = $db
->selectDistinct( 'tblUsers', 'userID as value, userID as label' )
->fetchAll();
}
// Echo
echo json_encode( $data );
}
The errors I receive when running this code are:
Errors {"error":"SQLSTATE[42S22]: Column not found: 1054 Unknown
column 'tblActions.id' in 'field
list'","data":[],"tblUsers":[{"value":"1","label":"1"},{"value":"2","label":"2"}]}
DataTables warning: table id=tblActions - Invalid JSON response. For
more information about this error, please see
http://datatables.net/tn/1.
This code was from a sample provide when downloading the Editor v1.3.1. I am somewhat familiar with the plug-in however find it perplexing when such an error occurs. Any help would be much appreciated.
Thanks :)
You have to change the name of the primary key.
I think if you add the following somewhere.
"idSrc": "actionID",
http://datatables.net/forums/discussion/19199/custom-primary-key
This also may work
$data = Editor::inst( $db, 'tblActions' )
->pkey( 'actionID' )

Codeigniter Datatables / table add data

i am newbie in web programming and datatables and i am trying to add new data to my tables using fnAddData() but it not work
here is my code
$('#btn_ubahbj').click( function() {
//inisialisasi table upproses
Otableupproses=$('#tableupproses').dataTable( {
'sDom': 't',
"bServerSide": false,
"sServerMethod": "POST",
"fnServerParams": function ( aoData ) {
aoData.push( { "name": "idbom", "value": window.id_bom } );
},
"sAjaxSource": "<?=base_url()?>index.php/master_bj/ambilbomproses",
"sAjaxDataProp": "callback",
"bDestroy": true,
"bAutoWidth": false,
"aoColumns": [
{ "sTitle": "ID Proses", "mDataProp": "id_proses_produksi"},
{ "sTitle": "Nama Proses", "mDataProp": "nama"},
{ "sTitle": "Lama Proses", "mDataProp": "waktu"},
{ "sTitle": "Jumlah Mesin", "mDataProp": "jumlah_mesin"},
]
} );
} );
$('#btnuptambahproses').click(
Otableupproses.fnAddData( [$('#prosesupbj').val(),$("#prosesupbj option:selected").text(),$('#txtuplamaproses').val(),$('#txtupjmlmesin').val()]
);
});
my controller name master_bj
function ambilbomproses()
{
$idbom= $this->input->post('idbom');
$res['dataproses']=$this->bom_punya_proses_model->getbomproses($idbom);
echo json_encode(array("callback" => $res['dataproses']));
}
how can i dinamically add new row ?
i use fnAddData() it not work because i get data from json
please help
my model class name bom_punya_proses_model
function getbomproses($idbom)
{
$sql= "SELECT proses_produksi_punya_bom.id_proses_produksi, proses_produksi.nama, proses_produksi_punya_bom.waktu, proses_produksi_punya_bom.jumlah_mesin
FROM proses_produksi_punya_bom
INNER JOIN proses_produksi ON proses_produksi_punya_bom.id_proses_produksi = proses_produksi.id_proses_produksi
WHERE proses_produksi_punya_bom.id_bom = '".$idbom."'";
$result= $this->db->query($sql);
if($result->num_rows() > 0){
return $result->result_array();
}else
return false;
}
no problem with my query and controller , because the json has been performed correctly , but the problem is when i try to add new row data to table ,
Your model does not appear to be using the active records portion of the codeigniter framework at all.
Check the tutorial on the CI website and have a look at the active record help page at :
http://ellislab.com/codeigniter/user-guide/database/active_record.html

Categories