kendo observable array sorting - kendo-ui

I have a observable array in a viewmodel.
I show the date of array with a template:
<table align="center">
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
</tr>
</thead>
<tbody data-template="row-template" data-bind="source: client"></tbody>
</table>
But if i want to sort array? and show the 'client' order by name or surname?

If your data array is like this (as json, if not convert to json or databind using server)
[{name:'name1',surname:'surname1'},{name:'name2',surname:'surname2'},{name:'name3',surname:'surname3'}]
You can use this code for client side sorting.
$("table").kendoGrid({
dataSource: {
data:[{name:'name1',surname:'surname1'},{name:'name2',surname:'surname2'},{name:'name3',surname:'surname3'}],
sort: {
field: "name",
dir: "desc"
}
},
sortable: true,
columns: [
{
field: "name",
title: "Name"
},
{
field: "surname",
title: "Surname"
}
]});
If i understand you right, this will solve your problem.

Related

Ajax load data in datatables and set data on button

everything works fine. The only issue that i cannot fix/find is how to create a button and set the value of data: cvpdf inside a href of a button to open the cv
The cvpdf is the file name of a cv stored in the database.
<table id="dtBasicExample" class="table table-striped custom-table mb-0 datatable " >
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>surname</th>
<th>email</th>
<th>position</th>
<th>CV</th>
</tr>
</thead>
<tbody id="atn-tbody">
</tbody>
</table>
function showInformation(str) {
console.log(str);
$("#dtBasicExample").dataTable().fnDestroy();
$(document).ready(function(){
$("#dtBasicExample").dataTable({
scrollX: true,
"ajax":{
url: "data.php?q="+str ,
dataSrc:"",
},
"columns":[
{"data": "id"},
{"data": "name"},
{"data": "surname"},
{"data": "email"},
{"data": "position"},
{"data": "cvpdf"},
]
});
});
};
Let me help you out with this. you can apply this to any column data
columns: [
{
data: function(row){
return `Click This`
}
}
]
the "row" parameter will return the whole data for the current row, so you can access the object through the "row.your_key".
this is the best practice to make your code simpler.
the complete parameter can be accessed through This Link
Hope it can help!

How to sort Datatable by days in string value

I am currently using Datatable in my laravel project for displaying my day configuration from my database. I would like to display my data in the following order, Monday -> Tuesday -> Wednesday etc.
Currently it is being ordered by alphabetical order from my database where the day column is store as string. Below are my javascript codes for my table.
var ophrTables = $('#ophrs_table').DataTable({
stateSave: true,
columnDefs: [{
"searchable": false,
"orderable": false,
"targets": 0
},{
"searchable": true,
"orderable": true,
"targets": 1
},{
"searchable": false,
"orderable": false,
"targets": 2
},{
"searchable": false,
"orderable": false,
"targets": 3
}],
order: [[ 1, 'asc' ]]
});
Here are two approaches:
Use a Column Renderer
You can create a mapping from day names to numbers:
var days = { 'Monday': 1, 'Tuesday': 2, 'Wednesday': 3, 'Thursday': 4, 'Friday': 5, 'Saturday': 6, 'Sunday': 7 };
You can then use that mapping when you create your DataTable.
Here is my test data in my HTML table:
<table id="example" class="display dataTable cell-border" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Day</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>Monday</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>Tuesday</td>
</tr>
<tr>
<td>Ashton Cox</td>
<td>Wednesday</td>
</tr>
<tr>
<td>Cedric Kelly</td>
<td>Thursday</td>
</tr>
<tr>
<td>Airi Satou</td>
<td>Friday</td>
</tr>
<tr>
<td>Brielle Williamson</td>
<td>Saturday</td>
</tr>
<tr>
<td>Herrod Chandler</td>
<td>Sunday</td>
</tr>
</tbody>
</table>
Here is my DataTable definition:
$('#example').DataTable( {
"columnDefs": [ {
"targets": 1,
"render": function ( data, type, row, meta ) {
if (type === 'sort') {
return days[data];
} else {
return data;
}
}
} ]
} );
For the second column (index = 1), I use a render function to map from the name of the day to an integer. DataTables will use this integer for sorting operations (type === 'sort'). Otherwise it will use the name of the day.
The days[data] expression is used to look up the relevant number from my days variable.
The data looks like this when it is sorted by day name:
Warning:
When you use a renderer which produces numeric sort data from data which is alphanumeric, you do have to be careful. Even though numbers are used for sorting, they are treated as alphanumeric. In our case, this makes no difference, because the string values "1" through "7" are sorted the same way as the integer values 1 through 7.
But if you wanted to do something similar with the months of the year, then you would run into problems, as October (10), November (11) and December (12) would potentially be mis-sorted.
One fix for this is to force the column to be treated as if it contains numeric data by default: "type": "num",. Credit to this answer for highlighting this potential issue.
(Forcing the return value to be an integer does not help: return parseInt(days[data]);).
Delegated Sorting
An alternative approach is to populate the relevant number into an extra column when you load your data into the table.
In your DataTable definition, you can hide this column:
"columnDefs": [
{ "visible": false, "targets": 2 }
]
Then you can use the DataTables orderData option to delegate sorting from the visible "day name" column to the hidden "day number" column:
"columnDefs": [
{ "visible": false, "targets": 2 },
{ "orderData": [ 1 ], "targets": 2 }
]
This tells DataTables to use the data in column index 2 when you sort on column index 1.
I don't think that you can order by day. May be you can put a hidden text in the datatable column.
Now
<td>Monday</td>
<td>Tuesday</td>
<td>Friday</td>
Change it to
<td><span style="display:none">1</span>Monday</td>
<td><span style="display:none">2</span>Tuesday</td>
<td><span style="display:none">5</span>Friday</td>
Once you change it to this style, you can order by day.

Initialization datatable via Ajax - No data displayed

I have a datatable that I would like to initialize with an Ajax call http://url/api/v1/shocks
table.blade.php
<div class="card-body p-0">
<div class="table-responsive">
<table class="table table-striped table-md" id="table-raw-shocks" width="100%" cellspacing="0">
<thead>
<tr>
<th>Record Id</th>
<th>Count</th>
<th>Date</th>
<th>Amplitude 1 (G)</th>
<th>Amplitude 2 (G)</th>
<th>Time 1 (s)</th>
<th>Time 2 (s)</th>
<th>Freq 1 (Hz)</th>
<th>Freq 2 (Hz)</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Record Id</th>
<th>Count</th>
<th>Date</th>
<th>Amplitude 1 (G)</th>
<th>Amplitude 2 (G)</th>
<th>Time 1 (s)</th>
<th>Time 2 (s)</th>
<th>Freq 1 (Hz)</th>
<th>Freq 2 (Hz)</th>
</tr>
</tfoot>
</table>
</div>
</div>
Javascript part
$(document).ready(function () {
initShocksActivityTable();
});
function initShocksActivityTable() {
var url = '{{ route("api:v1:shocks.index") }}'; //http://url/api/v1/shocks
var table = $('#table-raw-shocks-all').DataTable({
responsive: true,
responsive: {
details: {
type: "column",
target: "tr"
}
},
orderCellsTop: true,
fixedHeader: true,
dom: "Bfrtip",
buttons: ["copy", "csv", "excel", "pdf", "print"],
columnDefs: [{
sortable: true
}],
"ajax": url,
"columns": [{
"data": "attributes.record_id"
},
{
"data": "attributes.count"
},
{
"data": "attributes.date_time"
},
{
"data": "attributes.amplitude_1"
},
{
"data": "attributes.amplitude_2"
},
{
"data": "attributes.time_1"
},
{
"data": "attributes.time_2"
},
{
"data": "attributes.freq_1"
},
{
"data": "attributes.freq_2"
},
],
lengthMenu: [
[10, 25, 50, -1],
[10, 25, 50, "All"]
],
iDisplayLength: 10,
order: [
[2, "desc"]
]
});
}
My data looks like this :
Attributes contains all the necessary data that I would like to add on my datatable.
When I do that, I have no data displayed. I suspect that it is because, my data is an array ( [0], 1...)
I tried to add this piece of code (https://datatables.net/reference/option/ajax.dataSrc)
"dataSrc": "data.attributes"
But it still does not work.
I'm sure, it's something that I missed but I have some difficulties to find what is the problem to fetch correctly the data.
Could you please help me on that ? Thank

bllim/laravel4 datatables - not working

I am using Bllim Laravel for the first time.
I am not getting any error message but neither able to populate the data in datatable, I am getting the datatable but it has no data in it. Query is working fine and I can see the data in it but it doesn't get passed to Datatable or is not in the format that datatable is able to read
Posting code here:
Controller
public function listAjax() {
$posts = DB::table('newspaper')->select('id', 'no_of_pages', 'date', 'publishing_time', 'status');
return Datatables::of($posts, true)->make();}
View
<table id="newspaperList" class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>No of pages</th>
<th>Date</th>
<th>Publishing time</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function() {
$("#newspaperList").dataTable({
"processing": true,
"serverSide": true,
"ajax": "http://localhost:88/epaperlaravel/public/ep-admin/newspaper/listajax",
"order": [[1, 'desc']],
"columnDefs": [{//this prevents errors if the data is null
"targets": "_all",
"defaultContent": ""
}],
"columns": [
//title will auto-generate th columns
{"data": "id", "title": "Id", "orderable": true, "searchable": false},
{"data": "no_of_pages", "title": "Name", "orderable": true, "searchable": true},
{"data": "date", "title": "Username", "orderable": true, "searchable": true},
{"data": "publishing_time", "title": "Email", "orderable": true, "searchable": true},
{"data": "status", "title": "Created", "orderable": true, "searchable": true},
]
});
});
Route
Route::get('ep-admin/newspaper/listajax', array('as' => 'articlesajax', 'uses' => 'NewspaperController#listAjax'));
Where i am going wrong?
This much script is needed for displaying data :
$('#dataTables-example').DataTable( {
bProcessing: true,
bServerSide: true,
dom: "Tfrtip",
sAjaxSource: "{{ URL::to('/work/showusers') }}",
aaSorting : [[ 0, "desc" ]],
"aoColumns": [
{ 'sWidth': '60px' },
{ 'sWidth': '130px', 'sClass': 'center' },
{ 'sWidth': '180px', 'sClass': 'center' },
{ 'sWidth': '60px', 'sClass': 'center' },
],
tableTools: {
sRowSelect: "os",
aButtons: [
{ sExtends: "editor_create", editor: editor },
{ sExtends: "editor_edit", editor: editor },
{ sExtends: "editor_remove", editor: editor }
]
},
language: {
processing: "Traitement en cours...",
search: "Rechercher :",
lengthMenu: "Afficher _MENU_ éléments",
info: "Affichage de l'élement _START_ à _END_ sur _TOTAL_ éléments",
infoEmpty: "Affichage de l'élement 0 à 0 sur 0 éléments",
infoFiltered: "(filtré de _MAX_ éléments au total)",
infoPostFix: "",
loadingRecords: "Chargement en cours...",
zeroRecords: "Aucun élément à afficher",
emptyTable: "Aucune donnée disponible dans le tableau",
paginate: {
first: "Premier",
previous: "Précédent",
next: "Suivant",
last: "Dernier"
},
aria: {
sortAscending: ": activer pour trier la colonne par ordre croissant",
sortDescending: ": activer pour trier la colonne par ordre décroissant"
}
}
} );
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-hover" id="dataTables-example">
<thead>
<tr>
<th>ID</th>
<th>Username</th>
<th>Email</th>
<th>Password</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>Username</th>
<th>Email</th>
<th>Password</th>
</tr>
</tfoot>
</table>

Durandal and jqGrid

There is already an example of jqxGrid that is labeled "jqGrid integration with existing Durandal solution". However, I don't have the option of using jqxGrid.
Does any one have an example of using jqGrid with durandal. This is what I'm trying now and it is not working.
Unable to parse bindings.
Bindings value: attr: { href: 'animals/' + id, title: name }, text: id
Message: id is not defined;
viewmodel.js
///
define(['durandal/app', 'jqgrid', 'kojqgrid'], function (app) {
var initialData = [
{ id: 1, name: "Well-Travelled Kitten", sales: 352, price: 75.95 },
{ id: 2, name: "Speedy Coyote", sales: 89, price: 190.00 },
{ id: 3, name: "Furious Lizard", sales: 152, price: 25.00 },
{ id: 4, name: "Indifferent Monkey", sales: 1, price: 99.95 },
{ id: 5, name: "Brooding Dragon", sales: 0, price: 6350 },
{ id: 6, name: "Ingenious Tadpole", sales: 39450, price: 0.35 },
{ id: 7, name: "Optimistic Snail", sales: 420, price: 1.50 }
];
var ctor = function () {
this.animals = ko.observableArray([]);
this.disabled = ko.observable(false);
this.activate = function () {
this.animals(initialData);
return true;
}
};
//Note: This module exports a function. That means that you, the developer, can create multiple instances.
//This pattern is also recognized by Durandal so that it can create instances on demand.
return ctor;
});
View
-------------------------------------------------------------------
<h3>Customers</h3>
<table id="animals" data-bind="grid: { data: animals }" >
<caption>Amazing Animals</caption>
<thead>
<tr>
<th data-field="actions" style="width:27px;"></th>
<th data-field="name" width="150px">Item Name</th>
<th data-field="sales">Sales Count</th>
<th data-field="price">Price</th>
</tr>
</thead>
<tbody>
<tr>
<td data-field="actions">
<a class="grid-edit" data-bind="attr: { href: 'animals/' + id, title: name }, text: id"></a>
</td>
</tr>
</tbody>
</table>
Any help would be greatly appreciated.
The reason you are getting id is undefined is because the ctor function does not expose id or name attribute but the animals observableArray. In your view you need to loop over the animals obserbavbleArray to get access to id and name attribute for each animal. Try the following code:
<tbody data-bind='foreach:animals'>
<tr>
<td data-field="actions">
<a class="grid-edit" data-bind="attr: { href: 'animals/' + id, title: name }, text: id"></a>
</td>
</tr>
</tbody>
You need to put your activate handler on the prototype:
ctor.prototype.activate = function () {...}
Durandal likely cannot find your activate handler and, therefore, never initializes the data.
Also, I can only assume that the jqGrid binding is looking at the table definition and harvesting from the DOM what it needs to build a proper binding. The reason I say that is that, strictly speaking, #nimrig is right: there needs to be a foreach somewhere. It must be that the jqGrid is building that foreach.

Resources