How to modify csv data in amcharts export - amcharts

I want to modify csv data while export from amcharts.
Scenario is like : I have 2 column 1 with values and other with 0. Now i dont want that column to display in the csv which have 0 values.
I did not find anything for this.

You could use processData for that. See more here: https://github.com/amcharts/export#changing-the-dataprovider-when-exporting
"export": {
"enabled": true,
"processData": function (data, cfg) {
if (cfg.format === 'CSV') {
return data.map(function (item) {
// Ignore the second column
return {
firstColumn: item.firstColumn
};
});
}
return data;
}
}

The processData way is fine for datas that do not much differ to the dataProvider.
Amcharts's doc is not very well documented about this, but after a bit of digging, I found this way :
var myChart = AmCharts.makeChart('chart-id', {
dataProvider: myDatas, // Some datas
export: {
enabled: true,
// Using the 'menu' option in order to override its behavior ...
menu: [{
class: 'export-main',
menu: [{
label: 'Download as ...',
menu: ['PNG', 'JPG', 'SVG', 'PDF']
}, {
label: 'Save as ...',
menu: [{
label: 'CSV',
// Overriding CSV export behavior :
click: function exportCSV() {
// This will export the 'myDatas' datas to a string formatted as a CSV.
// Feel free to change the 'data' option of the 'toCSV()' method for a different CSV.
myChart.export.toCSV({ data: myDatas }, function(data) {
// 'data' is a string containing the CSV
// This will download the CSV to the file MyCSV.csv !
this.download(data, this.defaults.formats.CSV.mimeType, 'MyCSV.csv');
});
}
}]
}, {
label: 'Annotate ...',
action: 'draw',
menu: [{
class: 'export-drawing',
menu: ['PNG', 'JPG']
}]
}]
}]
}
});
This will export and download a CSV file with the desired datas !

Related

jqGrid: How to load only rows that an attribute is set to true

I have a JSON Object as the following:
{
"rows": [
{
"id":1,
"name": "Peter",
"hasData": true,
},
{
"id":2,
"name": "Tom",
"hasData": false,
}]
}
And I want the jqGrid to load only rows that have data, meaning when "hasData" == true.
I am firstly wondering what is the best way to do such and secondly wondering how to do it.
UPDATE:
I have tried the following:
gridComplete: function(){
var rowObjects = this.p.data;
for(var i = 0; i<rowObjects.length;i++){
if(rowObjects[i].hasData == false){
$(this).jqGrid('delRowData',rowObjects[i].id);
}
}
},
but the problem is when I go to the next page, all the data is loaded new from the JSON.
I suppose that you load the data from the server using datatype: "json" in combination with loadonce: true option. The solution is very easy if you use free jqGrid fork of jqGrid. Free jqGrid allows to sort and to filter the data, returned from the server, before displaying the first page of data. One need to add forceClientSorting: true to force the applying the actions by jqGrid and postData.filters with the filter, which you need, and the option search: true to apply the filter:
$("#grid").jqGrid({
...
datatype: "json",
postData: {
// the filters property is the filter, which need be applied
// to the data loaded from the server
filters: JSON.stringify({
groupOp: "AND",
groups: [],
rules: [{field: "hasData", op: "eq", data: "true"}]
})
},
loadonce: true,
forceClientSorting: true,
search: true,
// to be able to use "hasData" property in the filter one has to
// include "hasData" column in colModel or in additionalProperties
additionalProperties: ["hasData"],
...
});
See the demo https://jsfiddle.net/OlegKi/epcz4ptq/, which demonstrate it. The demo uses Echo service of JSFiddle to simulate server response.
I can recommend you another solution (in case you use Guriddo jqGrid) , which can be used with any datatype and any settings. The idea is to use beforeProcessing event to filter the needed data.
For this purpose we assume that the data is like described from you. Here is the code:
$("#grid").jqGrid({
...
beforeProcessing : function (data, st, xhr) {
var test= data.rows.filter(function (row) {
if(row.hasData == true ) { // true is not needed but for demo
return true;
} else {
return false;
}
});
data.rows = test;
return true;
}
...
});
I suppose the script will work in free jqGrid in case you use them

How to filter kendo grid data using filter specified for computed column

Have a look at this jsfiddle
I have a computed column (NewCol as mentioned in the below code) in the kendo grid - which has filter option enabled. The columns shows True/False based on the data of the other column.
schema: {
model: {
fields: {
OrderID: { type: "number" },
Freight: { type: "number" },
OrderDate: { type: "date" },
ShipCity: { type: "string" },
NewCol: {type: "string"}
}
}
}
The column definition in grid is,
{
field: "NewCol",
title: "Computed",
template: '#= (OrderDate > new Date(1996,6,10) ) ? "False" : "True" #'
}
Now, my issue is, the data are not getting filtered using that column filter i.e. True/False. If I filter with True/False, the grid goes empty.
I have tried defining function in datasource for the column as below, but then its not showing any data for the column.
NewCol: function () {
console.log(this.get('OrderDate'));
if (this.get('OrderDate') > new Date()) return 'False';
else return 'True';
},
Ans shows the js error Uncaught TypeError: undefined is not a function
There are two options. The first is compatible with your version of KendoUI, the second you will have to move to current one.
1st solution, define a schema.parse function that computes the new column on read time:
parse: function (data) {
var tgtDate = new Date(1996,6,10);
$.each(data.d.results, function(idx, elem) {
var d = parseInt(elem.OrderDate.substr(6));
elem.NewCol = (d > tgtDate ) ? "False" : "True";
});
return data;
}
From there, the column is like any other column received from the server so you can use it.
You can see you JSFiddle modified here http://jsfiddle.net/OnaBai/3TsGB/3/
2nd solution is use a new feature that allows to define a options.fields.fieldName.parse function for a field definition in the model and do something similar to what I did in the previous solution.

kendo grid delete command not working

i have developed a web application using kendo ui tools and theres a kendo grid with batch edit mode..
but when i press the delete button for any record in kendo grid it will erase from the list in grid but actually not in the data source.when i reload the page or grid the deleted item will still exist..
here is the code of my grid
<div id="grid">
</div>
<script type="text/javascript">
$("#submitMarketUser").click(function () {
var grid = $("#grid").data("kendoGrid");
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "WholeSaleTrade/GetTradeProductDetail",
dataType: "json",
data: {
test: $("#Names").val()
}
},
destroy: {
url: "WholeSaleTrade/DeletePro",
type: "POST",
dataType: "jsonp",
data: {
DAKy: $("#Names").val(),
DIKy: $("#btntxt").val()
}
},
create: {
url: "WholeSaleTrade/CreateProduct",
type: "POST",
dataType: "jsonp",
data: {
AKy: $("#Names").val(),
IKy: $("#btntxt").val()
}
}
},
pageSize: 5,
schema: {
model: {
id: "ProductKey",
fields: {
ProductKey: { editable: false, nullable: true },
ProductName: { validation: { required: true} }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
editable: true,
toolbar: ["create", "save"],
autobind: true,
pageable: true,
columns: [
{ field: "ProductName", title: "Product Name",
editor: function (container, options) {
var model = options.model;
$('<input id="btntxt" name="' + options.field + '"/>').appendTo(container).kendoComboBox({
dataSource: {
type: "POST",
transport: {
read: {
url: "MarketInformation/PopulateProducts",
success: function (data) {
var prod = data[0];
model.set("ProductName", prod.ItmNm);
model.set("ItmKy", prod.ItmKy);
model.set("UserKey", $("#Names").val());
}
}
}
},
dataValueField: "ItmKy",
dataTextField: "ItmNm"
});
}
},
{ command: ["destroy"], title: " " }
]
});
});
</script>
can not identify that where is the fault going and can somebody please help me to solve this matter.
There are three common reasons delete won't work:
1. Not setting editable of grid to inline or popup. The deleted items will be automatically processed through transport destroy only for "inline"/"popup" edit modes. Ex:
editable: {
mode: "inline",
}
//or
editable: "inline"
2. If on your datasource, you have the batch flag set to true, this means the datasource will make the call only after you tell it to, e.g calling sync(). Ex:
var dataSource = new kendo.data.DataSource({
batch: true,
//.....
});
//... in some where e.g in a save button click event call the following line:
dataSource.sync();
3. You should define id to your primary key of database field name inside model of datasource. Ex:
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
}
}
So the problem with your code is first one, i.e you did not set editable to inline or popup
If you choose not to include editable.mode in order to utilize the in-cell editing, you can set the toolbar of the grid to include the option save:
$("#grid").kendoGrid({
dataSource: {
transport: {
....
},
schema: {
....
}
},
toolbar: ["create", "save", "cancel"],
columns: [
....
],
editable: true
});
This will create a save button at the toolbar of the grid. After deleting any records by clicking the destroy command button, click on the save button to have the grid to make an Ajax call to the server to delete the record.
If you would rather delete the record automatically without including the save button, you could add a change event handler to the datasource of the grid:
$("#grid").kendoGrid({
dataSource: {
transport: {
....
},
schema: {
....
},
change: function(e) {
if (e.action === "remove") {
this.sync();
}
}
},
columns: [
....
],
editable: true
});
This will automatically sync the changes you made to the grid with the server when there's a data change.
Hmm try not including type: "POST", and see if it now works since as far as I can see that bit isn't included on the demo's and I don't think I included it when I last did inline edits/deletes.
I had put an arbitray name for an int on the server Delete Method.
[HttpPost]
public ActionResult DeleteRandomTest(Int32 randomTestId)
{
...
}
The default modelbinder was probably looking for a property called Id (same as the primary key of my type according to the configuration of the model).
.Model(config => config.Id(p => p.Id))
In fact, I proved this by changing the signature to the following:
[HttpPost]
public ActionResult DeleteRandomTest(Int32 Id)
{
...
}
My break point was hit after that.
Ultimately, I used the full type as the parameter as shown in the Kendo examples because I didn't want to have poorly named parameter names (not camel case) in the action. Shown as follows:
[HttpPost]
public ActionResult DeleteRandomTest([DataSourceRequest]
DataSourceRequest request, RandomDrugTest randomDrugTest)
{
...
}
This seems to the be the reason it wasn't working.
I had the same issue. My issue was caused by having a data property in the kendo model. Example:
{id: 1, data: ""}

KendoGrid Get modified column id

On my Kendo grid, I have "editable=true" and datasource with "autoSync=true". As I click on a cell, it becomes editable and when leaving the cell it executes the transport's update event.
That's all fine.
In the update event I have access to the row of the dataset model containing all the values of the modified row (although with editable=true and autosync, only one column value would have been modified).
I need to know which column / field was modified?
Ideally I thought that info would be in the arguments (options) supplied to the update event.
dataSource = new kendo.data.DataSource({
autoSync: true,
transport: {
update: function (options) {
// options does not tell me which model field was updated?
...
But since it isn't there, I suppose I need to bind to the model's set event, but I cannot get that to work.
Any ideas?
Never mind this answer! I read the question all wrong.
I think I got it working the way you like.
Is this jsFiddle what you're looking for?
var ds = new kendo.data.DataSource({
autoSync: true,
transport: {
read: function(options) {
options.success([
{ Id: 1, A: 'Hello', B: 'World' },
{ Id: 2, A: '1', B: '2' },
{ Id: 3, A: 'fdasf', B: '4523' }
]);
},
update: function (options) {
var uid = ds.data().find(function(p) {return p.Id == options.data.Id;}).uid;
var tr = $('#grid .k-grid-content tr[data-uid="'+uid+'"]');
console.log(tr);
//Do something with tr
}
},
schema: {
model: { id: "Id" }
}
});
$('#grid').kendoGrid({
dataSource: ds,
editable: true,
});

Creating a column in KendoGrid that is not bound to datasource

I am using Kendo UI to bind a datasource to the Kendo Grid. I am trying to find the best way to create a column in the grid that is not bound to the datasource.
Currently, I am creating a field in the datasource and using some javascript and jQuery to set the values of that column after the data is read from the remote endpoint.
Datasource:
schema: {
model: {
fields: {
blah: {},
empty_column: {}
}
}
}
Grid:
columns: {
field: "empty_column",
width: 100,
title: "Empty"
}
Javascript:
datasource.data[item].set("empty_column", computed_value);
All code edited for brevity, it all works fine.
My question: is there a way to set the defaultValue for this new, empty column which is not connected to the remote endpoint?
When I set:
empty_column: {defaultValue: "None"}
the grid still displays 'undefined', I think because it is not receiveing any data for that field in the read operation. Is there a way to set the defaultValue in the grid? I haven't seen any examples of this...
defaultValue applies when you create a record, not when it is going to be displayed.
You can do:
Option 1: use parse in schema.fields.fieldName that would be something like this.
model: {
fields: {
empty_column: {
type : "string",
defaultValue: "none",
parse : function (data) {
if (!data.empty_columns) {
data.empty_column = "none";
}
return data;
}
},
blah : { type: "number" }
}
},
Option 2: Use schema.parse for adding the extra field value.
schema: {
model: {
fields: {
empty_column: {type: "string", defaultValue: "none"},
blah : { type: "number" }
}
},
parse: function (response) {
$.each(response, function (idx, item) {
if (!item.empty_column) {
item.empty_column = "none";
}
});
return response;
}
}
Of course, (for both options) if you certainly know that there is no previous value in empty_column you might save the test condition and leave only the assignment.

Resources