Add unique id to every row using ag-Grid - javascript

I used the ag-Grid plugin in javascript for my grid. My problem is figuring out how I can update the rows into database. How can I set a unique id to every row?
<div id="myGrid" style="height: 600px;" class="ag-theme-balham"></div>
<script type="text/javascript" charset="utf-8">
// specify the columns
var columnDefs = [
{headerName: "Make", field: "make"},
{headerName: "Model", field: "model"},
{headerName: "Price", field: "price"}
];
// specify the data
var rowData = [
{make: "Toyota", model: "Celica", price: 'test', my_unique_id: '123'},
{make: "Ford", model: "Mondeo", price: 32000, my_unique_id: '42341'},
{make: "Porsche", model: "Boxter", price: 72000, my_unique_id: '567'}
];
// let the grid know which columns and what data to use
var gridOptions = {
columnDefs: columnDefs,
rowData: rowData
};
// lookup the container we want the Grid to use
var eGridDiv = document.querySelector('#myGrid');
// create the grid passing in the div to use together with the columns & data we want to use
new agGrid.Grid(eGridDiv, gridOptions);
</script>

On the definition of your columns columnDefs you need to add the key and, if you need, set hide: true to this data not appears on UI
var columnDefs = [
{headerName: "Make", field: "make"},
{headerName: "Model", field: "model"},
{headerName: "Price", field: "price"},
{headerName: "Key", field: "my_unique_id", hide = true},
];
See all properties for columns on ag-grid docs here: https://www.ag-grid.com/javascript-grid-column-properties/

I am not sure if you are aware of this, but ag-grid actually assigns a unique ID to every row, when the row data is set.
On of the ways to access the id for each row node would be to use the forEachNode() method, as specified within the ag-grid gridOptions API documentation. forEachNode() iterates all rows, and returns the data for each row.
Assuming you are using Vanilla JavaScript (without any frameworks such as React or Angular), you do the following to get the id
gridOptions.api.forEachNode(node => {
console.log(node.id);
// do the rest
});

{
headerName: "Num",
field: "id",
filter: true,
width: 150,
cellRendererFramework:(params)=>{
return <span>{params.rowIndex}</span>
}
},

Related

populating input field with row data when row is clicked on

How can i populate form inputs with the row data of a row that is clicked on? (using AG GRID and vanilla JS)
Example code would be appreciated
const gridOptions = {
columnDefs: [
{field: "make", sortable: true, filter: true},
{field: "model", sortable: true, filter: true},
{field: "price", sortable: true, filter: true}
],
rowData: [
{make: "VW", model: "Jetta", price: "$25,000"},
{make: "Honda", model: "Odyssey", price: "$35,000"},
{make: "Audi", model: "Q2", price: "$45,000"}
],
animateRows: true,
onCellClicked: params => {
let dataMake = params.data.make;
console.log(dataMake);
const fillInput = (e) => {
e.preventDefault()
const input1 = document.querySelector("#input1").value
console.log(input1);
input1 = "dataMake"
}
}
};
new agGrid.Grid(eGridDiv, gridOptions)
fetch("https://www.ag-grid.com/example-assets/row-data.json")
.then(res => res.json())
.then(data => {
gridOptions.api.setRowData(data)
});
I'm assuming that you know how to set values in your form, and that you're just asking how to get the data from the grid.
So, if I understand correctly, you're asking about filling in multiple form fields, corresponding to multiple cells in grid row, when the row is clicked.
Your code looks correct except that you are using the onCellClicked property where you should be using onRowClicked.
With onCellClicked the param to the callback is the data backing the cell that was clicked, while with onRowClicked the param is the object backing the entire row.

Using ag-grid correctly

Is it possible to use Ag-Grid javascript version with ASP.Net MVC Application,
If So, Please tell me how to use.
I tried the demo given in ag-grid site, AG-Grid.
But it is not working fine with asp.net, I am getting Error says
Uncaught TypeError: Cannot read property 'match' of undefined
at e.getTheme (ag-grid.min.js:242)
at e.specialForNewMaterial (ag-grid.min.js:20)
at e.getHeaderHeight (ag-grid.min.js:20)
at e.getGroupHeaderHeight (ag-grid.min.js:20)
at t.setBodyAndHeaderHeights (ag-grid.min.js:74)
at t.init (ag-grid.min.js:74)
at ag-grid.min.js:8
at Array.forEach (<anonymous>)
at ag-grid.min.js:8
at Array.forEach (<anonymous>)
I doubt if I am missing any other packages.
var rowData = [
{ make: "Toyota", model: "Celica", price: 35000 },
{ make: "Ford", model: "Mondeo", price: 32000 },
{ make: "Porsche", model: "Boxter", price: 72000 }
];
var columnDefs = [
{ headerName: "Make", field: "make" },
{ headerName: "Model", field: "model" },
{ headerName: "Price", field: "price" }
];
function doProcess() {
var gridOptions = {
rowData: rowData,
columnDefs: columnDefs,
onGridReady: function (params) {
params.api.sizeColumnsToFit();
}
};
new agGrid.Grid("#myGrid", gridOptions);
}
doProcess();
<!-- Inside the view page -->
<h2>Index</h2>
<script src="https://unpkg.com/ag-grid/dist/ag-grid.min.noStyle.js"></script>
<script src="https://unpkg.com/ag-grid#17.0.0/dist/ag-grid.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/ag-grid/dist/styles/ag-grid.css">
<link rel="stylesheet" href="https://unpkg.com/ag-grid/dist/styles/ag-theme-balham.css">
<div id="myGrid" style="height: 131px; width:600px;" ></div>
Looking at the blog shows that only ag-grid.min.noStyle.js is loaded in that demo, whereas you have loaded ag-grid.min.js as well. I would guess they are variants of the same thing, and this is almost certainly unnecessary. Also there is no apparent need for jQuery.
Lastly though, and most importantly, you created your grid like this:
new agGrid.Grid("#myGrid", gridOptions);
by passing in a selector string directly. However the demo (and no doubt the documentation, if you check it) clearly shows that a DOM element is passed in, created by using document.querySelector, i.e.
var eGridDiv = document.querySelector('#myGrid');
new agGrid.Grid(eGridDiv, gridOptions);
Since you passed the grid something it didn't understand, it can't load anything into it.
Working demo:
var rowData = [
{ make: "Toyota", model: "Celica", price: 35000 },
{ make: "Ford", model: "Mondeo", price: 32000 },
{ make: "Porsche", model: "Boxter", price: 72000 }
];
var columnDefs = [
{ headerName: "Make", field: "make" },
{ headerName: "Model", field: "model" },
{ headerName: "Price", field: "price" }
];
function doProcess() {
var gridOptions = {
rowData: rowData,
columnDefs: columnDefs,
onGridReady: function (params) {
params.api.sizeColumnsToFit();
}
};
var eGridDiv = document.querySelector('#myGrid');
new agGrid.Grid(eGridDiv, gridOptions);
}
doProcess();
<!-- Inside the view page -->
<h2>Index</h2>
<script src="https://unpkg.com/ag-grid#17.0.0/dist/ag-grid.min.noStyle.js"></script>
<link rel="stylesheet" href="https://unpkg.com/ag-grid/dist/styles/ag-grid.css">
<link rel="stylesheet" href="https://unpkg.com/ag-grid/dist/styles/ag-theme-balham.css">
<div id="myGrid" style="height: 131px; width:600px;" ></div>
N.B. If you're going to follow a demo, it's usually wise to follow it accurately, and only change things where you understand the consequences and actually need to change them to fulfil your own project's requirement. In the case of the changes you have made, most of them look unnecessary, including the one which caused the problem.

Agroup data using ag-grid

I am currently using ag-grid in my project. Am trying to agroup the data using the agrouping feature.
In my col def I have this:
{headerName: "Parent", field: "ParentID",width: 120,rowGroup:true},
{headerName: "Name", field: "Name"},
{headerName: "Level", field: "Level"},
{headerName: "Active", field: "Active"},
{headerName: "Actions",
field: "Actions",
cellRenderer: function (params) {
/*Generate a link and return it*/
return EditLink;
}
}
Then, the ag-grid options:
var gridOptions = {
columnDefs: columnDefs,
rowData: rowData,
onGridReady: function () {
gridOptions.api.sizeColumnsToFit();
},
animateRows: true,
enableRangeSelection: true,
enableSorting: true,
enableFilter: true,
enableColResize: true,
domLayout:'autoHeight',
rowHeight: 48,
enableStatusBar: true,
rowSelection: 'single',
groupMultiAutoColumn:true,
groupRemoveSingleChildren:true,
icons: {
checkboxChecked: '<img src="data:image/png;base64,SOMECODEHERE"/>'
}
};
However, I am not getting the expected behaviour, I have the table rendered with the data and the column to agroup the data, but it's not agrouped, it's like ordered but I don't see the button to dropdown the children
Are you sure the ParentID is shared amongst several rows? The groupRemoveSingleChildren option will show no groups if no ids are shared.
You can also try using rowGroupIndex as opposed to rowGroup
i.e
this.columnDefs = [
{headerName: "Clan", field: "clan", editable: true, rowGroupIndex: 0 },
The rowGroupIndex allows sub groups to be defined so you can nest groups (if you need to).
I would also recommend removing the groupRemoveSingleChildren just to see if you get the checkbox or whether the data is at fault..

Ag-grid with AngularJS - header width is not aligning with data columns

[Update] I will add an additional 200 points (total 300) if anyone gets my snippet working, with headers and data columns aligned.
This is my first attempt with ag-grid. I assign the grid header like this:
var stationAnalyticsColumnDefs = [
{headerName: "Station #", field: "station_id", width: 150, sort: 'asc'},
{headerName: "Station name", field: "station_name", width: 150, sort: 'desc'},
{headerName: "Total visitors", field: "total_visit_count", width: 150, sort: 'desc'},
{headerName: "Busiest day (visitors)", valueGetter: BusiestDayValueGetter, width: 150, comparator: BusiestDayComparator},
];
I am fetching the data by AJAX, so when my $http.get returns success, accoding to the docs, I should be able to
$scope.stationAnalyticsGridOptions.api.refreshView();
or
$scope.stationAnalyticsGridOptions.api.refreshRows(data);
but neither of those seems to work (no data is shown), so I use
$scope.stationAnalyticsGridOptions.api.setRowData(data);
and the data shows just fine.
My problem is that the headers don't align with the data. How do I do that? I also want the grid columns to resize as I drag the headers to resize them.
[Update] Still working on the Plunk. Can anyone see what's wrong with this?
View
<div ag-grid="stationAnalyticsGridOptions"
class="ag-fresh ag-basic"
style="height:400px; width:80%">
Controller
var stationAnalyticsColumnDefs = [
{headerName: "Station #", field: "station_id", width: 150, sort: 'asc'},
{headerName: "Station name", field: "station_name", width: 150, sort: 'desc'},
{headerName: "Total visitors", field: "total_visit_count", width: 150, sort: 'desc'},
{headerName: "Busiest day (visitors)", valueGetter: BusiestDayValueGetter, width: 150, comparator: BusiestDayComparator},
];
$scope.stationAnalyticsGridOptions = {
columnDefs: stationAnalyticsColumnDefs,
rowData: $scope.eventStationsAnalyticData,
enableColResize: true,
enableSorting: true,
enableFilter: true,
};
[Update] I tried to create a working Fiddle, to reproduce the question, but failed; the table does not even display. You can find the Fiddle at https://jsfiddle.net/mawg/9ex225ye/4/
Can anyone get it working - with the header width and data column width aligning?
Please fork my Fiddle, rather than starting from scratch, and retain the variable names, etc
Try setup your gridOptions including angularComileHeader: true to ensure your headers does work with AngularJS in the right way. Please check this runnable plnkr and compare it with your solution. Also ensure you using the latest version of ag-grid.
$scope.gridOptions = {
columnDefs: columnDefs,
rowData: $scope.rowData,
angularCompileHeaders: true,
enableColResize: true,
enableSorting: true,
enableFilter: true
};

Kendo grid not reponding to dataSource filtering

I have a kendo grid displaying data correctly. I want to add an input box where when user types something in the grid filters that data, like a search box functionality for the grid.
Initially i set the grid's data source:
$("#grid").data("kendoGrid").setDataSource(new kendo.data.DataSource({ data: result }));
filter is applied like this:
$("#grid").data("kendoGrid").dataSource.filter({
logic: 'or',
filters: [
{ field: 'lastName', operator: 'startswith', value: viewModel.get('searchValue') },
{ field: 'address', operator: 'startswith', value: viewModel.get('searchValue') }
]
});
and the input box:
<input data-bind="value: searchValue" />
However whenever the searchValue is changed, the dataSource remains the same, and the grid doesn't change.
Onchange function you may hookup below code
var kgrid = $("#grid").data("kendoGrid");
var orfilter = { logic: "or", filters: [] };
orfilter.filters.push({ field: "lastName", operator: "startswith", value: viewModel.get('searchValue') },
{ field: "address", operator: "startswith", value: viewModel.get('searchValue') });
kgrid.dataSource.filter(orfilter);

Categories

Resources