Related
var ColDef = [{
headerName: "colA",
field: 'colA',
rowGroup: true
},
{
headerName: "colB",
field: 'colB',
pivot: true,
enablePivot: true
},
{
headerName: "colC",
field: 'colC',
rowGroup: true
},
{
field: 'colD',
aggFunc: 'first',
valueFormatter: currencyFormatter,
tooltip: function(params) {
return (params.valueFormatted);
},
},
{
field: 'comment'
},
{
field: 'colF'
}
];
function currencyFormatter(params) {
return params.value;
}
above code is from different question. it works but i want to use different 'comment' field as tool tip to current 'colD' . also this is a group and pivot agGrid,if it is normal grid this is not a problem. I would appreciate any ideas for group and pivot agGrid?
Not sure if there is good way for the grid to get the data in your scenario then, as your rows and columns are different than original model after pivot.
Maybe you can consider retrieve this information outside of grid. Assume you also want some aggregated information displays in the tooltip, the tooltip function may eventually look like this:
tooltip: params => {
const country = params.node.key;
const year = params.colDef.pivotKeys[0];
const athletesWithNumbers = this.state.rowData
.filter(d => d.year == year)
.filter(d => d.country === country)
.filter(d => d.gold > 0)
.map(d => d.athlete + ': ' + d.gold);
return athletesWithNumbers.join(', ');
}
See this plunker for what I am talking about - again, not sure if this is what you want but just an FYI.
just use tooltipValueGetter
{
field: 'message',
headerName: 'Message',
headerTooltip: 'Message',
width: 110,
filter: 'agSetColumnFilter',
tooltipValueGetter: (params) => `${params.value} some text`
}
or just use the same method for tooltipValueGetter
UPDATE:
Okay, I understood
but it also easy
Ag-grid has property tooltipField - where you can choose any field from grid
For example here - in the column of 'sport' I am showing tooltip of the previous column
Example: https://plnkr.co/edit/zNbMPT5HOB9yqI08
OR
You can easily manipulate with data for each field by tooltipValueGetter
with next construction:
tooltipValueGetter: function(params) {
return `Country: ${params.data.country}, Athlete: ${params.data.athlete}, Sport: ${params.data.sport}`;
},
Example: https://plnkr.co/edit/zNbMPT5HOB9yqI08
Result:
UPDATE 2
Hey Man! I do not understand was is wrong
I just used your code snippet and my solution
And it works as you want
Example: https://plnkr.co/edit/zNbMPT5HOB9yqI08
UPDATE 3
A little bit of manipulation and I can get the data
{ field: 'gold', aggFunc: 'sum',
tooltipValueGetter: function(params) {
var model = params.api.getDisplayedRowAtIndex(params.rowIndex);
return model.allLeafChildren[0].data.silver;
},
},
The Last:
https://plnkr.co/edit/9qtYjkngKJg6Ihwb?preview
var ColDef = [{
headerName: "colA",
field: 'colA',
rowGroup: true
},
{
headerName: "colB",
field: 'colB',
pivot: true,
enablePivot: true
},
{
headerName: "colC",
field: 'colC',
rowGroup: true
},
{
field: 'colD',
aggFunc: 'last',
tooltipValueGetter: commentTooltipValueGetter
},
{
field: 'comment'
},
{
field: 'colF'
}
];
function commentTooltipValueGetter(params) {
const colB = params.colDef.pivotKeys[0];
var model = params.api.getDisplayedRowAtIndex(params.rowIndex);
for (var i = 0; i < model.allLeafChildren.length ; i++) {
if (model.allLeafChildren[i].data.colB=== colB) {
return model.allLeafChildren[i].data.comments;
}
}
}
This is what i had to do for my question. It is combination of answers from #wctiger and #shuts below. So please also refer them for more context
I use multi-row grouping and put the totals in the grouping headers.
I'm not using the totals in the totals rows. I see the the rows are grouped and where the totals would be there are empty rows. In my case there is an empty row after each of the child grouping and at the end there is an empty row for the parent totals.
How do I remove these totals rows?
Thank you!
.cshtml:
<div id="gridList" class="grid" style="width: 100%; height: 500px"></div>
.js
$(function() {
var columns = [
{
id: "isExcluded",
name: "Exclude",
field: "isExcluded" /*, width: 120*/,
formatter: Slick.Formatters.Checkmark,
editor: Slick.Editors.Checkbox, sortable: true
},
{
id: "symbol",
name: "Symbol",
field: "symbol",
sortable: true /*, width: 120*/
},
{
id: "price",
name: "Price",
field: "price",
sortable: true
//, groupTotalsFormatter: sumTotalsFormatter
},
{
id: "parent_name",
name: "Parent Name",
field: "parent_name",
sortable: true /*, width: 120*/
},
{
id: "description",
name: "Description",
field: "description",
sortable: true,
width: 120,
editor: Slick.Editors.Text,
},
{ id: "cancel_ind",
name: "Canceled",
field: "cancel_ind",
sortable: true, width: 80 }
];
function requiredFieldValidator(value) {
if (value == null || value == undefined || !value.length) {
return { valid: false, msg: "This is a required field" };
} else {
return { valid: true, msg: null };
}
};
var options = {
editable: true,
enableAddRow: true,
enableCellNavigation: true,
asyncEditorLoading: false,
autoEdit: true,
enableExpandCollapse: true,
rowHeight: 25
};
var sortcol = "parent_name";
var sortdir = 1;
var grid;
var data = [];
var groupItemMetadataProviderTrades = new Slick.Data.GroupItemMetadataProvider();
var dataView = new Slick.Data.DataView({ groupItemMetadataProvider: groupItemMetadataProviderTrades });
dataView.onRowCountChanged.subscribe(function (e, args) {
grid.updateRowCount();
grid.render();
});
dataView.onRowsChanged.subscribe(function (e, args) {
grid.invalidateRows(args.rows);
grid.render();
});
function groupByParentAndSymbol() {
dataViewTrades.setGrouping([
{
getter: "parent_name",
formatter: function(g) {
return "Parent: " + g.value + " <span style='color:green'>(" + g.count + " items) Total: " + g.totals.sum.price + "</span>";
},
aggregators: [
new Slick.Data.Aggregators.Sum("price")
],
aggregateCollapsed: true
,lazyTotalsCalculation: true
},
{
getter: "symbol",
formatter: function(g) {
return "Symbol: " + g.value + " <span style='color:green'>(" + g.count + " items) Total: " + g.totals.sum.price + "</span>";
},
aggregators: [
new Slick.Data.Aggregators.Sum("price")
],
collapsed: true
,lazyTotalsCalculation: true
}]);
};
grid = new Slick.Grid("#gridList", dataView, columns, options);
grid.registerPlugin(groupItemMetadataProviderTrades);
grid.setSelectionModel(new Slick.RowSelectionModel());
..... /*sorting support etc*/
// use instead of the default formatter <--- removed not used.
function sumTotalsFormatter(totals, columnDef) {
var val = totals.sum && totals.sum[columnDef.field];
//if (val != null) {
// return "total: " + ((Math.round(parseFloat(val) * 100) / 100));
//}
return "";
}
// will be called on a button click (I didn't include the code as irrelevant)
var getDataList = function () {
$.getJSON('/Home/GetData/', function (json) {
data = json;
dataView.beginUpdate();
dataView.setItems(data);
groupByParentAndSymbol();
dataView.endUpdate();
dataView.syncGridSelection(grid, true);
});
};
getDataList();
});
Adding displayTOtalsRow: false to the dataview solved my problem - the total rows are not shown now.
var dataView = new Slick.Data.DataView({ groupItemMetadataProvider: groupItemMetadataProviderTrades, displayTotalsRow: false });
To answer simply to your question... Just remove the aggregators: [...], when I say remove you have 2 options, you can remove whatever is the array [...] or you could simply erase completely that object line (so removing completely the aggregators[...]).
Now if you want more explanation of how it works...Let's give you some definition so you'll understand better. An aggregate is a collection of items that are gathered together to form a total quantity. The total in question could be a sum of all the fields, an average or other type of aggregator you might define. So basically it's the action of regrouping by the column you chose and give the calculation result of the group. Alright now how does it work in the case of a SlickGrid? You need to define what kind of Aggregator you want to use (Avg, Sum, etc...) that goes inside your function groupByParentAndSymbol(), defining them will do the calculation BUT unless you attach it to the field, nothing will be displayed, so in the example you found it is very important to attach/bind this groupTotalsFormatter: sumTotalsFormatter to your columns definition, as for example:
...var columns = [{id: "cost", ...width: 90, groupTotalsFormatter: sumTotalsFormatter}, ...];
so let's recap... Once the Aggregator is define new Slick.Data.Aggregators.Sum("cost") it will do the calculation but unless it's bind to the field nothing will be displayed. As an extra option, the aggregateCollapsed (true/false) is to display the sub-total (avg, sum or whatever) inside or outside the group when you collapse.
is there any way to pass some additional data to the series object that will use to show in the chart 'tooltip'?
for example
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%b %e', this.x) +': '+ this.y;
}
here we can only use series.name , this.x & this.y to the series. lets say i need to pass another dynamic value alone with the data set and can access via series object. is this possible?
Thank you all in advance.
Yes, if you set up the series object like the following, where each data point is a hash, then you can pass extra values:
new Highcharts.Chart( {
...,
series: [ {
name: 'Foo',
data: [
{
y : 3,
myData : 'firstPoint'
},
{
y : 7,
myData : 'secondPoint'
},
{
y : 1,
myData : 'thirdPoint'
}
]
} ]
} );
In your tooltip you can access it via the "point" attribute of the object passed in:
tooltip: {
formatter: function() {
return 'Extra data: <b>' + this.point.myData + '</b>';
}
}
Full example here: https://jsfiddle.net/burwelldesigns/jeoL5y7s/
Additionally, with this solution, you can even put multiple data as much as you want :
tooltip: {
formatter: function () {
return 'Extra data: <b>' + this.point.myData + '</b><br> Another Data: <b>' + this.point.myOtherData + '</b>';
}
},
series: [{
name: 'Foo',
data: [{
y: 3,
myData: 'firstPoint',
myOtherData: 'Other first data'
}, {
y: 7,
myData: 'secondPoint',
myOtherData: 'Other second data'
}, {
y: 1,
myData: 'thirdPoint',
myOtherData: 'Other third data'
}]
}]
Thank you Nick.
For time series data, especially with enough data points to activate the turbo threshold, the proposed solutions above will not work. In the case of the turbo threshold, this is because Highcarts expects the data points to be an array like:
series: [{
name: 'Numbers over the course of time',
data: [
[1515059819853, 1],
[1515059838069, 2],
[1515059838080, 3],
// you get the idea
]
}]
In order not to lose the benefits of the turbo threshold (which is important when dealing with lots of data points), I store the data outside of the chart and look up the data point in the tooltip formatter function. Here's an example:
const chartData = [
{ timestamp: 1515059819853, value: 1, somethingElse: 'foo'},
{ timestamp: 1515059838069, value: 2, somethingElse: 'bar'},
{ timestamp: 1515059838080, value: 3, somethingElse: 'baz'},
// you get the idea
]
const Chart = Highcharts.stockChart(myChart, {
// ...options
tooltip: {
formatter () {
// this.point.x is the timestamp in my original chartData array
const pointData = chartData.find(row => row.timestamp === this.point.x)
console.log(pointData.somethingElse)
}
},
series: [{
name: 'Numbers over the course of time',
// restructure the data as an array as Highcharts expects it
// array index 0 is the x value, index 1 is the y value in the chart
data: chartData.map(row => [row.timestamp, row.value])
}]
})
This approach will work for all chart types.
I am using AJAX to get my data from SQL Server, then I prepare a js array that is used as the data in my chart.
JavaScript code once the AJAX is successfull:
...,
success: function (data) {
var fseries = [];
var series = [];
for (var arr in data) {
for (var i in data[arr]['data'] ){
var d = data[arr]['data'][i];
//if (i < 5) alert("d.method = " + d.method);
var serie = {x:Date.parse(d.Value), y:d.Item, method:d.method };
series.push(serie);
}
fseries.push({name: data[arr]['name'], data: series, location: data[arr]['location']});
series = [];
};
DrawChart(fseries);
},
Now to show extra meta-data in the tooltip:
...
tooltip: {
xDateFormat: '%m/%d/%y',
headerFormat: '<b>{series.name}</b><br>',
pointFormat: 'Method: {point.method}<br>Date: {point.x:%m/%d/%y } <br>Reading: {point.y:,.2f}',
shared: false,
},
I use a DataRow to iterate through my result set, then I use a class to assign the values prior to passing back in Json format. Here is the C# code in the controller action called by Ajax.
public JsonResult ChartData(string dataSource, string locationType, string[] locations, string[] methods, string fromDate, string toDate, string[] lstParams)
{
List<Dictionary<string, object>> dataResult = new List<Dictionary<string, object>>();
Dictionary<string, object> aSeries = new Dictionary<string, object>();
string currParam = string.Empty;
lstParams = (lstParams == null) ? new string[1] : lstParams;
foreach (DataRow dr in GetChartData(dataSource, locationType, locations, methods, fromDate, toDate, lstParams).Rows)
{
if (currParam != dr[1].ToString())
{
if (!String.IsNullOrEmpty(currParam)) //A new Standard Parameter is read and add to dataResult. Skips first record.
{
Dictionary<string, object> bSeries = new Dictionary<string, object>(aSeries); //Required else when clearing out aSeries, dataResult values are also cleared
dataResult.Add(bSeries);
aSeries.Clear();
}
currParam = dr[1].ToString();
aSeries["name"] = cParam;
aSeries["data"] = new List<ChartDataModel>();
aSeries["location"] = dr[0].ToString();
}
ChartDataModel lst = new ChartDataModel();
lst.Value = Convert.ToDateTime(dr[3]).ToShortDateString();
lst.Item = Convert.ToDouble(dr[2]);
lst.method = dr[4].ToString();
((List<ChartDataModel>)aSeries["data"]).Add(lst);
}
dataResult.Add(aSeries);
var result = Json(dataResult.ToList(), JsonRequestBehavior.AllowGet); //used to debug final dataResult before returning to AJAX call.
return result;
}
I realize there is a more efficient and acceptable way to code in C# but I inherited the project.
Just to add some kind of dynamism :
Did this for generating data for a stacked column chart with 10 categories.
I wanted to have for each category 4 data series and wanted to display additional information (image, question, distractor and expected answer) for each of the data series :
<?php
while($n<=10)
{
$data1[]=array(
"y"=>$nber1,
"img"=>$image1,
"ques"=>$ques,
"distractor"=>$distractor1,
"answer"=>$ans
);
$data2[]=array(
"y"=>$nber2,
"img"=>$image2,
"ques"=>$ques,
"distractor"=>$distractor2,
"answer"=>$ans
);
$data3[]=array(
"y"=>$nber3,
"img"=>$image3,
"ques"=>$ques,
"distractor"=>$distractor3,
"answer"=>$ans
);
$data4[]=array(
"y"=>$nber4,
"img"=>$image4,
"ques"=>$ques,
"distractor"=>$distractor4,
"answer"=>$ans
);
}
// Then convert the data into data series:
$mydata[]=array(
"name"=>"Distractor #1",
"data"=>$data1,
"stack"=>"Distractor #1"
);
$mydata[]=array(
"name"=>"Distractor #2",
"data"=>$data2,
"stack"=>"Distractor #2"
);
$mydata[]=array(
"name"=>"Distractor #3",
"data"=>$data3,
"stack"=>"Distractor #3"
);
$mydata[]=array(
"name"=>"Distractor #4",
"data"=>$data4,
"stack"=>"Distractor #4"
);
?>
In the highcharts section:
var mydata=<? echo json_encode($mydata)?>;
// Tooltip section
tooltip: {
useHTML: true,
formatter: function() {
return 'Question ID: <b>'+ this.x +'</b><br/>'+
'Question: <b>'+ this.point.ques +'</b><br/>'+
this.series.name+'<br> Total attempts: '+ this.y +'<br/>'+
"<img src=\"images/"+ this.point.img +"\" width=\"100px\" height=\"50px\"/><br>"+
'Distractor: <b>'+ this.point.distractor +'</b><br/>'+
'Expected answer: <b>'+ this.point.answer +'</b><br/>';
}
},
// Series section of the highcharts
series: mydata
// For the category section, just prepare an array of elements and assign to the category variable as the way I did it on series.
Hope it helps someone.
Hi i am having problem with my highcharts 'series' options. i initialized the chart options as below:
var options = {
chart: {
renderTo: 'chart',
defaultSeriesType: 'line',
},
title: {
text: 'Weight Monitor',
},
xAxis: {
title: {
text: 'Date Measurement'
},
categories: []
},
yAxis: {
title: {
text: 'Weight (in Lbs)'
}
},
series: []
};
I kept the categories: [] blank so that i can put the values in categories later. Same thing i did with my series options. I kept the data:[] as blank to fill it later. Now i wrote the code to fill the data.
var lines = [
[2011,150],
[2012,121],
$.each(lines, function(lineNo, line) {
var items = line.toString().split(",");
$.each (items, function(itemNo, item) {
if(itemNo == 0){
alert("itemNo: " + itemNo + " item: " + item);
options.xAxis.categories.push(item);
alert(options.xAxis.categories);
}
else {
var series = {
data: []
};
alert("itemNo: " + itemNo + " item: " + item);
options.series.data.push(parseFloat(item));
alert(options.series.data);
};
});
});
var chart = new Highcharts.Chart(options);
Now when i execute this code, my categories[] is getting values properly, but the execution gets stuck when it is at "options.series.data.push(parseFloat(item))". I am getting the proper value in the "alert("itemNo: " + itemNo + " item: " + item);". but just after that it hangs while pushing the item in series.data[]
any idea what is the problem. and i am running this javascript in php project so don't know if there is any issue because of the language. thanks
The problem is options.series.data.push(parseFloat(item)).
If you look at your options object, you can see that your series array is empty. You can ad series object in your options definition as follows -
series: [{
data: []
}]
Also the line
var series = {
data: []
};
is of no use.
On debug. when execution is leaving the controller I debug and the variable contains :
?sArray
{string[17, 2]}
[0, 0]: "Arecleoch"
[0, 1]: "21"
[1, 0]: "Barnesmore"
[1, 1]: "3"
etc etc....
then in the javascript its received as :
?sdata
{...}
[0]: "Arecleoch"
[1]: "21"
[2]: "Barnesmore"
[3]: "3"
[4]: "Beinn An Tuirc"
[5]: "1"
[6]: "Beinn An Tuirc Phase 2"
etc
so the pie is displayed as one solid circle of colour
puzzled, any ideas?
controller code below :
public JsonResult GetChartData_IncidentsBySite()
{
var allSites = _securityRepository.FindAllSites();
var qry = from s in _db.Sites
join i in _db.Incidents on s.SiteId equals i.SiteId
group s by s.SiteDescription
into grp
select new
{
Site = grp.Key,
Count = grp.Count()
};
string[,] sArray = new string[qry.Count(),2];
int y = 0;
foreach (var row in qry.OrderBy(x => x.Site))
{
if ((row.Count > 0) && (row.Site != null))
{
sArray[y, 0] = row.Site.ToString();
sArray[y, 1] = row.Count.ToString();
y++;
}
}
return Json(sArray , JsonRequestBehavior.AllowGet);
}
Here is the javascript code :
$.getJSON(url, null, function(sdata) {
debugger;
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Number of Environmental Incidents by Site'
},
tooltip: {
formatter: function() {
return '<b>' + this.point.name + '</b>: ' + this.y + ' %';
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
type: 'pie',
name: 'Incidents by Site',
data: sdata
}]
});
});
});
In the version that works, data is an Array of Arrays of String ;
data: [["Arecleoch",21], ...
(Notice there is no oppening quotes before the first bracket).
In the version that does not work, it is a String representing the Array.
I suspect the charts API only expect an Array (in this case, an array of array, actually).
So it depends on what this does :
$.getJSON(url, null, function(data) {
// What is the type of data here ?
From your controller and the display of your debugger, I think data is itself an Array of Arrays. You should directly pass it to the charts API (without the sData = data.toString()) function wich actually transforms the Array ['a', 'b', 'c'] into a String representing the array, like "['a', 'b', 'c']");
// Callback parameter renamed to show it is an Array of Arrays
$.getJSON(url, null, function(aaData) {
// ... skipped ...
series: [{
type: 'pie',
name: 'Incidents by Site',
data: aaData /* Use the Array itself */
}]
Edit : my solution will only work if the controller output something like :
{
data : [[ "Arecleoch", 21], ["Whatever", 42]]
}
However it seems like your controller returns something like
{
data : "[['Arecleoch', 21],['Whatever', 42]]"
}
(Maybe without the { data : } part, I don't know if you need a top-level element or if you are derectly returning the Array in JSON)
Is that the case ? If so, then you'll have to either :
change the controller
parse the string on the client side, in javascript