vue-good-table custom sorting - vue.js

I am using vue-good-table and have the following code so far:
<vue-good-table :columns="columns" :rows="rows"
styleClass="vgt-table condensed striped bordered"
:sort-options="sortOptions"
:search-options="searchOptions"
:select-options="selectOptions"
#on-selected-rows-change="selectionChanged">
</vue-good-table>
sortOptions: {
enabled: true,
initialSortBy: { field: "date", type: "desc" },
}
columns() {
return [
{
label: "Name",
field: "name",
},
{
label: "CreationDate",
field: "date",
type: "date",
formatFn: function (value) {
return value != null ? moment(value).format('YYYY-MM-DD') : null;
},
sortFn(x, y) {
x = moment(x);
y = moment(y);
return x.unix() < y.unix() ? -1 : x.unix() > y.unix() ? 1 : 0;
},
},
]
}
Sorting works fine so far, and there are three states: 'asc', 'desc' and 'none'.
However i would like to achieve the following:
When clicking the column header and the current sorting type is 'none' for any of the columns, i would like to have the data sorted as defined in the initialSortBy property in the sortOptions. So sorted by date in desc order.
I tried using the #on-sort-change event but don't really know how to proceed further as i am quite new to Vue.
onSortChange(params) {
console.log('on-sort-change:');
console.log(params[0].field)
console.log(params[0].type)
if (params[0].type == 'none') {
console.log("default sort")
//TODO sort data as defined in initial sort
}
}

Related

Button onClick inside DataTables doesn't show the correct url

I'm displaying all the customer data using DataTables like this:
<script type="text/javascript" src="DataTables/datatables.min.js"></script>
<script>
var theTable = null;
$(document).ready(function() {
theTable = $('#table-customer').DataTable({
"processing": true,
"serverSide": false,
"ordering": true,
"order": [[ 0, 'asc' ]],
"ajax":
{
"url": "http://localhost/myshop/showdata.php",
"type": "GET"
},
"sAjaxDataProp": "data",
"deferRender": true,
"aLengthMenu": [[5, 10, 20, 50],[ 5, 10, 20, 50]],
"columns": [
{ data: "cust_id" },
{ data: "cust_name" },
{ data: "cust_addr" },
{ data: "cust_email" },
{ data: "cust_phone" },
{ data: "cust_photo", sortable: true, render: function (o) { return '<button id="btn1" onclick="displayImage(data)">Show</button>';}
]
});
});
function displayImage(link){
window.alert(link);
}
</script>
All information is displayed properly, except 1 thing: if you click any button on "customer photo" column, instead of showing an alert which shows its URL, nothing happens. Inspecting the page showed me this:
Uncaught ReferenceError: data is not defined
at HTMLButtonElement.onclick (view.html:1)
How to fix this?
The columns.data render function builds a string which is returned:
function (o) { return 'your string here, including data value'; }
You have to (a) concatenate your data variable with the string literals you need; and (b) use the variable name you provided - I will use data instead of o:
function (data) { return 'your string here, including ' + data + ' value'; }
So, if we provide all the possible parameters allowed in the renderer, that becomes:
{
"data": "cust_photo",
"sortable": true,
"render": function(data, type, row, meta) {
return '<button id="btn1" onclick="displayImage(\'' + data + '\')">Show</button>';
}
}
I use \' to ensure the value of the data variable is surrounded in single quotes.
(Note that in your question, the code is also missing a closing }.)
But to avoid potential issues with sorting and filtering, these column data render functions need to account for DataTable's use of orthogonal data.
The type parameter can be used for this:
{
"data": "cust_photo",
"sortable": true,
"render": function(data, type, row, meta) {
if (type === 'display') {
return '<button id="btn1" onclick="displayImage(\'' + data + '\')">Show</button>';
} else {
return data; // type is for sorting or filtering - just use the raw value
}
}
}

YADCF custom_func not calling custom function

I have a database field that contains either integer 1 (representing the value 'document') or integer 2 (representing the value 'email') and I use datatables to format/display these integers as the words 'document' or 'email' within the table column. I would therefore like to use YADCF to be able to select 'document' or 'email' and have datatables filter the resultset accordingly.
Link to screen shot of table column.
I have used the custom_func feature as follows (code stripped down for brevity), but regardless of all other aspects of the datatable looking and working correctly, with a filter selector looking as expected and holding the selected value, and no console errors, my custom function is not being called. I have tried manually calling the custom function immediately before initialising YADCF, to check the scope, and it is being called just fine. Can anyone see anything obviously wrong please?
$(document).ready(function() {
function customFilterDocEmail(filterVal, columnVal) {
alert('customFilterDocEmail called');
var found;
if (columnVal === '') {
return true;
}
switch (filterVal) {
case 'doc':
found = columnVal === '1';
break;
case 'email':
found = columnVal === '2';
break;
default:
found = 1;
break;
}
if (found !== -1) {
return true;
}
return false;
}
})
var table = $('#table').DataTable({
serverSide: true,
processing: true,
ajax: {
url: '/api/datatables/getJson/doctext/doctexts',
type: 'POST',
data: function(d) {d.CSRFToken = '****';}
},
stateSave: true,
responsive: true,
pageLength: 25,
order: [[0, 'asc']],
columns: [
{ data: 'txt_type', width: '10%' },
{ data: 'txt_title' },
{ data: 'txt_name', width: '20%' },
{ data: 'link', orderable: false, width: '5%' },
],
}
});
yadcf.init(table, [
{ column_number: 0, filter_type: 'custom_func', custom_func: customFilterDocEmail,
data: [{ value: 'doc', label: 'Document' }, { value: 'email', label: 'Email' }] },
{ column_number: 1, column_data_type: 'text', filter_type: 'text', filter_delay: 500, filter_default_label: '', },
{ column_number: 2, column_data_type: 'text', filter_type: 'text', filter_delay: 500, filter_default_label: '', },
], 'footer');
YADCF Version: 0.9.3.beta.11
DataTables Version: 1.10.16
UPDATE: I haven't a clue what I'm doing wrong above, but I have come up with a little hack that saves having to use 'custom_func' and a custom filter. I've used the standard 'select' filter type but intercepted the filter string within the filter() method of my DatatablesSSP script thus:
$str = $requestColumn['search']['value'];
// returned search values for doctext 'txt_type' are Document/Email, so we need to map these to 1/2.
if ($column['db'] == 'txt_type') {
if ($str == 'Document') { $str = '1'; }
if ($str == 'Email') { $str = '2'; }
}
This works a treat :)
You have to place the customFilterDocEmail function outside of the $(document).ready block so it will be global and yadcf will see it

How DataTables determine columns type

I have a dynamic table enhanced by jQuery DataTables, which display a custom object similar to this example.
JSON:
{
"data": [
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": {
"display": "SomeString",
"timestamp": 1303686000
},
"office": "Edinburgh",
"extn": "5421"
},
// ... skipped ...
]}
JavaScript:
$(document).ready(function() {
$('#example').DataTable( {
ajax: "data/orthogonal.txt",
columns: [
{ data: "name" },
{ data: "position" },
{ data: "office" },
{ data: "extn" },
{ data: {
_: "start_date.display",
sort: "start_date.timestamp"
} },
{ data: "salary" }
]
} );
} );
The difference is that I dynamically build the columns configuration, because the columns can be in any order, and others columns can be added or removed from the list. For this example (my case is very similar) the problem is that for some reason the timestamp property is ordered as a String instead of being ordered as a number.
I discovered that after setting the column "type" as "number" the ordering works perfectly. I'm presuming that DataTables is auto detecting the column as "String" for some reason (maybe because the display element is a string).
How does DataTables set the type of the columns, when is not explicitly declared?
Edit 1
I made a sample code to show the problem
http://jsfiddle.net/Teles/agrLjd2n/16/
jQuery DataTables has built-in mechanism for type detection. There are multiple predefined functions for various types with fallback to string data type.
It's also possible to use third-party plug-ins or write your own.
There are multiple ways to specify data type, below are just the few.
SOLUTION 1
Use type option.
$(document).ready(function() {
$('#example').DataTable( {
ajax: "data/orthogonal.txt",
columns: [
{ data: "name" },
{ data: "position" },
{ data: "office" },
{ data: "extn" },
{ data: "start_date.display", type: "date" },
{ data: "salary" }
]
} );
} );
SOLUTION 2
Use returned JSON data for type detection, see columns.data for more information.
$(document).ready(function() {
$('#example').DataTable( {
ajax: "data/orthogonal.txt",
columns: [
{ data: "name" },
{ data: "position" },
{ data: "office" },
{ data: "extn" },
{ data: {
_: "start_date.display",
sort: "start_date.timestamp",
type: "start_date.timestamp",
} },
{ data: "salary" }
]
} );
} );
DataTables always check the "type" property of the column "data" to auto detect the type of the column, if no "type" property is specified it will check the default value "_".
So if you want DataTables to auto detect the type of the column checking the type of your "sort" property you should set the "type" property of data to be equals to your "sort" value
Here is a sample code with different approchs to achieve what I was tryng to do. Thanks #Gyrocode.com and #davidkonrad.
var Cell = function(display, value) {
this.display = display;
this.value = value;
}
$(document).ready(function() {
var cells = [
new Cell("120 (10%)", 120),
new Cell("60 (5%)", 60),
new Cell("30 (2.5%)", 30)
];
$('#example').DataTable( {
data: cells,
columns: [
{
title : "Column NOT OK",
data: {
_: "display",
sort: "value"
}
}, {
type : "num",
title : "Column Ok setting column type",
data: {
_: "display",
sort: "value"
}
}, {
title : "Column Ok changing default value",
data: {
_: "value",
display: "display",
filter: "display"
}
}, {
title : "Column Ok setting data type",
data: {
_: "display",
sort: "value",
type: "value"
}
}, {
type : "num",
title : "Column Not OK",
data: "display"
}
]
} );
} );

ExtJs4+: can calculated model field be editable?

My model has two data fields: persistent and calculated:
Ext.define('My.model.Value', {
extend: 'Ext.data.Model',
idProperty: 'id',
fields: [
{ name: 'id', type: 'auto' },
{ name: 'percentage', type: 'float' }, // values in 0..1 range
{ name: 'percentageDecimal', type: 'float', persist: false,
calculate: function(v) {
v = v.percentage;
return Ext.isNumber(v) ? v * 100.0 : v;
}
}
]
});
The percentageDecimal field is used in a grid and it is editable.
Question: how can I change my model to automatically update percentage field everytime the percentageDecimal is updated?
I use ExtJs 5.0.1.
I used #adaskos' suggestion as follows:
Ext.define('My.model.Value', {
extend: 'Ext.data.Model',
idProperty: 'id',
fields: [
{ name: 'id', type: 'auto' },
{ name: 'percentage', type: 'float' }, // values in 0..1 range
{ name: 'percentageDecimal', type: 'float', persist: false,
calculate: function(v) {
v = v.percentage;
return Ext.isNumber(v) ? v * 100.0 : v;
}
}
],
set: function (fieldName, value, options) {
if (Ext.isString(fieldName)) {
// single field update
if (fieldName === 'percentageDecimal') {
this.set('percentage', Ext.isNumber(value) ? 0.01 * value : value);
return;
}
} else {
// multiple fields update
if (Ext.isDefined(fieldName.percentageDecimal)) {
var data = Ext.clone(fieldName);
data.percentage = Ext.isNumber(data.percentageDecimal)
? 0.01 * data.percentageDecimal
: data.percentageDecimal;
delete data.percentageDecimal;
this.set(data);
return;
}
}
this.callParent(arguments);
}
});
I don't know if they added an automated way to do this in 5.0.1, but you can always override the set method and whenever an update occurs to percentageDecimal, you recalculate the percentage.
An alternative I prefer: if you expect enough updates but all you want is to display it in a grid, you can remove the extra computed field from the model and set your column with dataIndex: 'percentageDecimal' and change its renderer function to display it as you like (as a decimal).
Like below:
... , { text: 'Percentage', dataIndex: 'percentageDecimal'
, renderer: function (v) {
return Ext.isNumber(v) ? v * 100.0 : v;
}
}
You should use the config options depends to have this updated automatically!
And use the function convert instead of calculate (not sure if it work with calculate, i need to test)
See http://docs.sencha.com/extjs/5.1/5.1.0-apidocs/#!/api/Ext.data.field.Field-cfg-depends

Kendo UI BarChart Data Grouping

Not sure if this is possible. In my example I am using json as the source but this could be any size. In my example on fiddle I would use this data in a shared fashion by only binding two columns ProductFamily (xAxis) and Value (yAxis) but I would like to be able to group the columns by using an aggregate.
In this example without the grouping it shows multiple columns for FamilyA. Can this be grouped into ONE column and the values aggregated regardless of the amount of data?
So the result will show one column for FamilyA of Value 4850 + 4860 = 9710 etc.?
A problem with all examples online is that there is always the correct amount of data for each category. Not sure if this makes sense?
http://jsfiddle.net/jqIndy/ZPUr4/3/
//Sample data (see fiddle for complete sample)
[{
"Client":"",
"Date":"2011-06-01",
"ProductNumber":"5K190",
"ProductName":"CABLE USB",
"ProductFamily":"FamilyC",
"Status":"OPEN",
"Units":5000,
"Value":5150.0,
"ShippedToDestination":"CHINA"
}]
var productDataSource = new kendo.data.DataSource({
data: dr,
//group: {
// field: "ProductFamily",
//},
sort: {
field: "ProductFamily",
dir: "asc"
},
//aggregate: [
// { field: "Value", aggregate: "sum" }
//],
//schema: {
// model: {
// fields: {
// ProductFamily: { type: "string" },
// Value: { type: "number" },
// }
// }
//}
})
$("#product-family-chart").kendoChart({
dataSource: productDataSource,
//autoBind: false,
title: {
text: "Product Family (past 12 months)"
},
seriesDefaults: {
overlay: {
gradient: "none"
},
markers: {
visible: false
},
majorTickSize: 0,
opacity: .8
},
series: [{
type: "column",
field: "Value"
}],
valueAxis: {
line: {
visible: false
},
labels: {
format: "${0}",
skip: 2,
step: 2,
color: "#727f8e"
}
},
categoryAxis: {
field: "ProductFamily"
},
legend: {
visible: false
},
tooltip: {
visible: true,
format: "Value: ${0:N0}"
}
});​
The Kendo UI Chart does not support binding to group aggregates. At least not yet.
My suggestion is to:
Move the aggregate definition, so it's calculated per group:
group: {
field: "ProductFamily",
aggregates: [ {
field: "Value",
aggregate: "sum"
}]
}
Extract the aggregated values in the change handler:
var view = products.view();
var families = $.map(view, function(v) {
return v.value;
});
var values = $.map(view, function(v) {
return v.aggregates.Value.sum;
});
Bind the groups and categories manually:
series: [ {
type: "column",
data: values
}],
categoryAxis: {
categories: families
}
Working demo can be found here: http://jsbin.com/ofuduy/5/edit
I hope this helps.