I am new to DataTables Server Side Processing.
How can I join/combine two database column (db) in one datatables column (dt) using the server side script ? I tried:
$columns = array(
array( 'db' => 'id', 'dt' => 'id' ),
array( 'db' => array('firstname', 'lastname'),'dt' => 'priest' )
);
and it's NOT working. What is the right what to do that? Thank you!
I'm using DataTables-1.10.16.
You can also do it server side and then hide the column you don't want in js.
For example let's say you have a table with 3 columns: id, name and link.
To combine the link into the name do:
In html (header and footer) show both columns (we will hide the column dynamically in javascript):
<th>#</th><!--this is column 0 with id-->
<th>name</th><!--this is column 1 with name including a tag-->
<th>link</th><!--this is column 2 with link-->
In javascript:
$(document).ready(function() {
$('#table_id').DataTable(
"processing": true,
"serverSide": true,
"ajax": {
"url": "ajax.php"
},
"order": [[ 0, "asc" ]],//ordering by the id (usefull)
{"columnDefs": [
{ "visible": false, "targets": [ 0 ] },//hiding the id
{ "visible": false, "targets": [ 2 ] }//hiding the link column
]
});
});
In the ajax php script also describe both columns:
$columns = array(
array( 'db' => 'id', 'dt' => 0),
array(
'db' => 'name',
'dt' => 1,
'formatter' => function( $d, $row ) {
return ''.$d.'';
}
),
array( 'db' => 'link', 'dt' => 2 )
);
Sorry for late answer,
Actually in demo spss.php class you cannot merge them but we have a solution,
Which is using "Column Render"
Go to Server Side Processing file and
write a something like that (16 just assuming if you've 5 column u should write 6)
array( 'db' => 'database column', 'dt' => 16 )
Then go to the client;
$(document).ready(function() {
$('#example').DataTable( {
"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
"render": function ( data, type, row ) {
return data +' ('+ row[16]+')';
},
"targets": 11
},
//This is makes db 16 row nonvisible
{ "visible": false, "targets": [ 16 ] }
],
} );
} );
"Targets":11 means i would like add something to 11. column.
Related
I am using unclead / yii2-multiple-input widget.
I want to generate different number of rows with values from my database.
How can i do this?
I can design my columns in view and edit data manualy after page generated. But miss how to program the number of rows and its values in the view.
My code in view:
<?= $form->field($User, 'User')->widget(MultipleInput::className(), [
'min' => 0,
'max' => 4,
'columns' => [
[
'name' => 'name',
'title' => 'Name',
'type' => 'textInput',
'options' => [
'onchange' => $onchange,
],
],
[
'name' => 'birth',
'type' => \kartik\date\DatePicker::className(),
'title' => 'Birth',
'value' => function($data) {
return $data['day'];
},
'options' => [
'pluginOptions' => [
'format' => 'dd.mm.yyyy',
'todayHighlight' => true
]
]
],
]
])->label(false);
How can I make (for example) 8 rows with different values, and also have the ability to edit/remove/update some of them?
You need to look into the documentation as it says that you need to assign a separate field into the model which will store all the schedule in form of JSON and then provide it back to the field when editing/updating the model.
You have not added the appropriate model to verify how are you creating the field User in your given case above. so, i will try to create a simple example which will help you implement it in your scenario.
For Example.
You have to store a user in the database along with his favorite books.
User
id, name, email
Books
id, name
Create a field/column in you User table with the name schedule of type text, you can write a migration or add manually.
Add it to the rules in the User model as safe.
like below
public function rules() {
return [
....//other rules
[ [ 'schedule'] , 'safe' ]
];
}
Add the widget to the newly created column in ActiveForm
see below code
echo $form->field($model,'schedule')->widget(MultipleInput::class,[
'max' => 4,
'columns' => [
[
'name' => 'book_id',
'type' => 'dropDownList',
'title' => 'Book',
'items' => ArrayHelper::map( Books::find()->asArray()->all (),'id','name'),
],
]
]);
When saving the User model convert the array to JSON string.
like below
if( Yii::$app->request->isPost && $model->load(Yii::$app->request->post()) ){
$model->schedule = \yii\helpers\Json::encode($model->schedule);
$model->save();
}
Override the afterFind() of the User model to covert the json back to the array before loading the form.
like below
public function afterFind() {
parent::afterFind();
$this->schedule = \yii\helpers\Json::decode($this->schedule);
}
Now when saved the schedule field against the current user will have the JSON for the selected rows for the books, as many selected, for example, if I saved three books having ids(1,2,3) then it will have json like below
{
"0": {
"book_id": "1"
},
"2": {
"book_id": "2"
},
"3": {
"book_id": "3"
}
}
The above JSON will be converted to an array in the afterFind() so that the widget loads the saved schedule when you EDIT the record.
Now go to your update page or edit the newly saved model you will see the books loaded automatically.
I'm using Yajra Laravel Datatables for my data display with serverside ajax loads, to prevent long loads on large amounts.
Now I want to color single TD in a row depending on the status (and other options)
I found that I can easily add parametes to the whole row, depending on options:
->setRowAttr([
'style' => function($item){
return $item->disabled ? 'background-color: #ff0000;' : 'background-color: #00ff00;';
}
])
And this produces me:
But I don't need to color the whole row, only the Bookings TD (in this case) since a different color will be applied for the Active statuses + another one for Room groups, like this:
How can this be accomplished?
PS: I'm using Laravel 5.3 with Datatavles 6
Ok, solved this myself after reading this documentation
http://datatables.net/release-datatables/examples/advanced_init/row_callback.html:
First I added additional columns before Datatables make() call, since the original get overwritten with language outputs, like this:
->addColumn('active', function ($item) {
return $item->disabled ? 0 : 1;
})
->editColumn('disabled', function ($item) {
$item->disabled ? t('No') : t('Yes');
})
Then I added check to JS part right after data call:
serverSide: true,
ajax: {
url: ...,
type: "get"
},
columns: [
...
{data: 'disabled', name: 'disabled'},
...
],
createdRow: function ( row, data, index ) {
...
if ( data['active'] == 1 ) {
$('td', row).eq(5).addClass('success');
} else {
$('td', row).eq(5).addClass('danger');
}
...
},
Pls refer
php:
DataTables::of($query)
->addColumn('stylesheet', function ($record) {
return [
[
'col' => 11,
'style' => [
'background' => '#080',
],
],
[
'col' => 12,
'style' => [
'background' => '#c00',
'color' => '#fff',
],
],
];
});
javascript:
DataTable({
columns: [...],
createdRow: function (row, data, dataIndex, cells) {
if (data.stylesheet) {
$.each(data.stylesheet, function (k, rowStyle) {
$(cells[rowStyle.col]).css(rowStyle.style);
});
}
},
})
Result:
i have a problem with jquery datatable pagination (Server side processing).
For example i have a 24 records in database. The count is displaying correctly and total pagination also displaying correctly.
when i click on Next or 2nd page it displays records as per the display page length.
Here 3rd Page last 4 records are not displayed.
Here my server side code is like this
$this->db->select("SQL_CALC_FOUND_ROWS user_id,user_name,email", FALSE);
$this->db->from("users");
$sTable="users";
// Data set length after filtering
$this->db->select('FOUND_ROWS() AS found_rows');
$iFilteredTotal = $this->db->get('users')->row()->found_rows;
// Total data set length
$iTotal = $this->db->count_all($sTable);
// Output
$output = array(
'sEcho' => intval($sEcho),
'iTotalRecords' => $iTotal,
'iTotalDisplayRecords' => $iFilteredTotal,
'aaData' => array()
);
Client side Code like this
$(document).ready(function () {
$('#data_appraiser').dataTable({
"bProcessing": true,
"bServerSide": true,
"oLanguage": {
"sProcessing": imgsrc,
},
//"aaData": data.aaData,
"iDisplayLength": 10,
"aLengthMenu": [
[10, 25, 50],
[10, 25, 50] // change per page values here
],
"aaSorting": [[0, 'asc']],
"sServerMethod": "POST",
"sAjaxSource": "appraiserlistajaxdata",
"sPaginationType": "full_numbers"
"aoColumns": [
{ "mData": "id" },
{ "mData": "appraiser_name" },
{ "mData": "user_name" }
....
]
});
});
I checked with $iFilteredTotal total count.when the page changes the value is 20.If it is in 1st page the value is 24.i am unable to solve this problem. Sorry if my problem was weired.Could any one help me how to resolve this issue. Thanks
You have to take start and length (like $_GET['start'])as the offset and limit respectively and apply in the query.
the problem here is the dataTables pagination is not working
this is the script i created that outputs json from the database
include( "../database.php" );
$q = $dbh->prepare("SELECT r.studid, r.firstname, r.middlename, r.lastname, r.Enrolling, c.courseid,c.code, s.status,s.dateapproved,s.approvedby FROM pcc_registration r, pcc_courses c, pcc_studentsubj s WHERE c.courseid= r.Enrolling AND s.studentid=r.studid AND r.status=? AND s.status=? GROUP BY r.studid");
$q->execute(array(1,2));
$rows = array();
$i = 1;
while ($r = $q->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT, PDO::FETCH_COLUMN)){
$rows[] = array(
"DT_RowId" => "row_".$i,
"reg" => array(
"studid" => $r[0],
"firstname" => $r[1],
"middlename" => $r[2],
"lastname" => $r[3],
"course" => $r[6],
"dateapproved" => $r[8],
"approvedby" => $r[9]
),
);
$i++;
}
$rt = (STRING) $q->rowCount();
$data = array(
"draw" => 2,
"recordsTotal" => $rt,
"recordsFiltered" => $rt,
"data" => $rows
);
echo json_encode($data);
and this is the javascript that outputs the json encoded data to the page
(function($) {
$(document).ready(function() {
$('#dataTables-example').DataTable( {
processing: true,
serverSide: true,
ajax: {
url: "includes/php/approvedSched.php",
type: "POST"
},
"deferRender": true,
columns: [
{data: "reg.studid"},
{data: "reg.lastname"},
{data: "reg.firstname"},
{data: "reg.middlename"},
{data: "reg.course"},
{data: "reg.dateapproved"},
{data: "reg.approvedby"},
{data: "reg.studid"},
],
tableTools: {
sRowSelect: "os",
aButtons: [
// {sExtends: "editor_edit", editor: editor},
// {sExtends: "editor_remove", editor: editor}
]
}
} );
});
}(jQuery));
any answer or solution to this problem is appreciated =)
http://datatables.net/manual/server-side
http://coderexample.com/datatable-demo-server-side-in-phpmysql-and-ajax/
this links is a better help for custom server side with mySQL
Where is the problem exactly? Is it just the DataTable pagination, or is it related with the MySQL query? I mean, does it show the rows and the problem is just the pagination, or it doesn't show anything at all?
I had some issues 'transferring' the query result from php to js as JSON (I'm a complete web programming noob), but DataTables' pagination didn't gave me any problem...
I used the following code for datatable:
$('#example').dataTable( {
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [0] },
{ "sType": "numeric", "aTargets": [ 5 ] }
],
"aaSorting": [[ 1, 'asc' ]]
} );
Here for the 5th column. I used the sort type as 'numeric', but the sorting is not working for this column. The column values are:
$205.22
$247.24
$869.95
$215
......
What's wrong here? Please help me.
A dollar sign isn't numeric. That might be your problem.
I believe datatables offers a currency sorting plugin.
edit in response: Add the dollar sign after you finish the sort (or look into the currency sorting plugin I mentioned)