AG Grid - Add rows of data to Master Detail without using JSON file - ag-grid

I wanted to know how to add rows of data to the master detail table but not using an external json file and just write the row records inline via the JS
Anyone have any idea on how to go about this
https://www.ag-grid.com/documentation/javascript/master-detail/
var gridOptions = {
columnDefs: [
// group cell renderer needed for expand / collapse icons
{ field: 'name', cellRenderer: 'agGroupCellRenderer' },
{ field: 'account' },
{ field: 'calls' },
{ field: 'minutes', valueFormatter: "x.toLocaleString() + 'm'" },
],
defaultColDef: {
flex: 1,
},
masterDetail: true,
detailCellRendererParams: {
detailGridOptions: {
columnDefs: [
{ field: 'callId' },
{ field: 'direction', minWidth: 150 },
{ field: 'number' },
{ field: 'duration', valueFormatter: "x.toLocaleString() + 's'" },
{ field: 'switchCode', minWidth: 150 },
],
defaultColDef: {
flex: 1,
},
},
getDetailRowData: function (params) {
// simulate delayed supply of data to the detail pane
setTimeout(function () {
params.successCallback(params.data.callRecords);
}, 1000);
},
},
};
// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', function () {
var gridDiv = document.querySelector('#myGrid');
new agGrid.Grid(gridDiv, gridOptions);
// I dont want to use the external json file
agGrid
.simpleHttpRequest({
url: 'https://www.ag-grid.com/example-assets/master-detail-data.json',
})
.then(function (data) {
gridOptions.api.setRowData(data);
});
});

Set the rowData field on the gridOptions like so:
var gridOptions = {
columnDefs: [
// group cell renderer needed for expand / collapse icons
{ field: 'name', cellRenderer: 'agGroupCellRenderer' },
{ field: 'account' },
{ field: 'calls' },
{ field: 'minutes', valueFormatter: "x.toLocaleString() + 'm'" },
],
defaultColDef: {
flex: 1,
},
masterDetail: true,
detailCellRendererParams: {
detailGridOptions: {
columnDefs: [
{ field: 'callId' },
{ field: 'direction' },
{ field: 'number', minWidth: 150 },
{ field: 'duration', valueFormatter: "x.toLocaleString() + 's'" },
{ field: 'switchCode', minWidth: 150 },
],
defaultColDef: {
flex: 1,
},
},
getDetailRowData: function (params) {
params.successCallback(params.data.callRecords);
},
},
onFirstDataRendered: onFirstDataRendered,
rowData: myData
};
In this instance, myData would look like this:
var myData = [
{
name: 'Nora Thomas',
account: 177000,
calls: 24,
minutes: 25.65,
callRecords: [
{
name: 'susan',
callId: 555,
duration: 72,
switchCode: 'SW3',
direction: 'Out',
number: '(00) 88542069',
},
],
},
];
Demo.

Related

echarts stacked bar chart with time xaxis

Can someone check my chart options and suggest a way to make the time xaxis behave correctly? I've tried with timestamps, dates, timestamps / 1000 and nothing looks right
let sales = [
0,84,5,3,2,1,0,0,3,6
]
let listings = [
1,297,23,5,8,6,9,3,6,19
]
let ps = [
1663084060653,
1663089644329,
1663095228005,
1663100811680,
1663106395356,
1663111979032,
1663117562708,
1663123146384,
1663128730059,
1663134313735
]
let color = "red"
option = {
textStyle: {
color
},
legend: {
textStyle: {
color
},
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: [
{
type: 'time',
data: ps,
// axisLabel: {
// formatter: ts => new Date(ts).toTimeString().replace(/ .*/, '')
// }
}
],
yAxis: [
{
// type: 'value'
}
],
series: [
{
name: 'Sales',
type: 'bar',
stack: 'Ad',
emphasis: {
focus: 'series'
},
data: sales
},
{
name: "Listings",
type: 'bar',
stack: 'Ad',
emphasis: {
focus: 'series'
},
data: listings
}
]
}
Your series (listings & sales here) have to have a [date, value] format. Also, you'll have to remove data from xAxis as it will automatically follow the dates that are given in the series.
So, in your example :
//convert listings & sales to a list of [date, value]
listings = listings.map((value, index) => {
return [ps[index], value]
})
sales = sales.map((value, index) => {
return [ps[index], value]
})
xAxis: [
{
type: 'time',
//data: ps, <--- remove this line
}
],

ExtJs 5 bind store to cell editor in grid

I'm trying to bind store to combobox editor in grid. My view is subclass of grid with cellediting plugin. I'm trying to bind at least static store with yes/no option. I tried many options and nothing worked.
Grid class:
Ext.define('App.view.school.room.RoomGrid', {
extend: 'Ext.grid.Panel',
alias: 'widget.school-room-grid',
controller: 'school-room-grid',
requires: [
'App.view.school.room.RoomGridController',
'App.view.school.room.RoomGridViewModel',
'Ext.button.Button',
'Ext.grid.plugin.CellEditing',
'Ext.grid.Panel',
'Ext.picker.Color',
'Ext.toolbar.Paging',
'Ext.toolbar.Toolbar'
],
reference: 'roomGrid',
viewModel: {
type: 'room'
},
bind: {
store: '{rooms}',
title: '{currentRoom.name}'
},
border: false,
itemId: 'testGrid',
glyph: 0xf0ce,
forceFit: true,
plugins: [
{
ptype: 'cellediting',
pluginId: 'editing'
}
],
header: {
title: 'Title',
padding: '4 9 4 9'
},
columns: [
//...
{
xtype: 'gridcolumn',
dataIndex: 'general',
text: 'SomeColumnYesNo',
editor:{
xtype: 'combobox',
bind: {
value:'{currentRoom.general}',
store:'{yesnoCombo}' //not working
},
displayField : 'name',
valueField : 'id',
selectOnFocus: true
}
}
],
buttons: [
{
itemId: 'addButton',
xtype: 'button',
width: 70,
scale: 'small',
text: 'Dodaj',
glyph: 0xf067
},
{
itemId: 'printButton',
xtype: 'button',
width: 70,
scale: 'small',
text: 'Drukuj',
glyph: 0xf02f
},
{
xtype: 'tbfill'
},
{
itemId: 'rejectButton',
xtype: 'button',
width: 22,
scale: 'small',
text: 'Anuluj',
glyph: 0xf021,
bind: {
disabled: '{!storeDirty}'
}
},
{
itemId: 'saveButton',
xtype: 'button',
width: 22,
scale: 'small',
text: 'Zapisz',
glyph: 0xf00c,
bind: {
disabled: '{!storeDirty}'
}
}
],
initComponent: function () {
me.callParent(arguments);
},
});
ViewModel class:
Ext.define('App.view.school.room.RoomGridViewModel', {
extend: 'Ext.app.ViewModel',
alias: 'viewmodel.room',
requires: [
'App.store.RoomStore',
'App.store.BuildingStore',
'App.store.TeacherStore',
'App.store.local.YesNoStore'
],
stores: {
//...
yesnoCombo:{
type:'local.yesnostore'
}
},
data: {
currentRoom: null
}
});
ViewController class:
Ext.define('App.view.school.room.RoomGridController', {
extend: 'Deft.mvc.ViewController',
alias: 'controller.school-room-grid',
requires: [
'App.view.school.room.RoomGridViewModel'
],
inject: [
'viewContext'
],
bind: {
currentRoom: '{currentRoom}',
store: '{rooms}'
},
config: {
currentRoom: null,
/** #type App.store.RoomStore */
roomStore: null,
/** #type App.context.ViewContext */
viewContext: null
},
control: {
'#': {
boxready: 'onBoxReady',
select: 'onSelect'
},
'#addButton': {
click: 'onAddButtonClick'
},
'#rejectButton': {
click: 'onRejectButtonClick'
},
'#saveButton': {
click: 'onSaveButtonClick'
}
},
onStoreLoading: function () {
Deft.Logger.info(this.$className + '.onStoreLoading');
var me = this;
me.getView().setLoading(true);
},
onStoreLoaded: function () {
Deft.Logger.info(this.$className + '.onStoreLoaded');
var me = this;
me.getView().setLoading(false);
},
//...
}
static store:
Ext.define('Perykles.store.local.YesNoStore', {
extend:'Ext.data.Store',
fields: ['id', 'name'],
autoLoad:false,
alias: 'store.local.yesnostore',
data : [
{"id":"true", "name":"Tak"},
{"id":"false", "name":"Nie"}
]
});
When I click on column binded to store to edit value instead of showing yes/no option in combobox i receive following error:
[E] Cannot modify ext-empty-store
Object
console.trace()
Uncaught Error: Cannot modify ext-empty-store
Any help would be appreciated.

Submit all of grid rows with Extjs form submit

I have a grid panel in a form. Any row of the grid panel have a filefield. I want to send any row (name field and filename field) to server.
Model:
Ext.define('FM.model.DefineCode', {
extend: 'Ext.data.Model',
fields: [
{name: 'id', type: 'int'},
{name: 'name', type: 'string'},
{name: 'filename', type: 'string'}
],
validations: [
{type: 'presence', field: 'id'},
{type: 'presence', field: 'name'},
{type: 'presence', field: 'filename'}
]
});
Store:
Ext.define('FM.store.DefineCode', {
extend: 'Ext.data.Store',
model: 'FM.model.DefineCode',
autoLoad: true,
data: []
});
View:
Ext.define('FM.view.map.DefineCode', {
extend: 'Ext.window.Window',
title: 'Define Code',
alias: 'widget.mmDefineCode',
width: 600,
modal: true,
items: [{
xtype: 'form',
items: [{
xtype: 'gridpanel',
title: 'myGrid',
store: 'DefineCode',
columns: [
{
text: 'Id',
xtype: 'rownumberer',
width: 20
}, {
text: 'Name',
dataIndex: 'name',
flex: 1,
editor:{
xtype: 'textfield'
}
}, {
text: 'File',
dataIndex: 'filename',
width: 200,
editor:{
xtype: 'filefield',
emptyText: 'Select your Icon',
name: 'photo-path',
buttonText: '',
flex: 1,
buttonConfig: {
iconCls: 'icon-upload-18x18'
},
listeners: {
change: function(e, ee, eee) {
var grid = this.up('grid');
var store = grid.getStore();
var newStore = Ext.create('FM.store.DefineCode',{});
store.insert(store.data.items.length, newStore);
}
}
},
}, {
text: '',
width: 40
}
],
height: 200,
width: 600,
plugins: [
Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 1
})
]}
],
}],
buttons: [{text: 'OK', action: 'OK'}],
initComponent: function() {
var me = this;
Ext.apply(me, {});
me.callParent(arguments);
}
});
Controller:
...
form.submit({
url: 'icon/create',
});
When I submit form, only last row is sending to server.
Where is problem?
Why you using this ?
var newStore = Ext.create('FM.store.Path', {});
store.insert(store.data.items.length, newStore);
try using rowEditing to edit/submit 1 row data :
var rowEditing = Ext.create('Ext.grid.plugin.RowEditing', {
clicksToEdit: 2,
clicksToMoveEditor: 1,
listeners: {
'validateedit': function(editor, e) {},
'afteredit': function(editor, e) {
var me = this;
var jsonData = Ext.encode(e.record.data);
Ext.Ajax.request({
method: 'POST',
url: 'your_url/save',
params: {data: jsonData},
success: function(response){
e.store.reload({
callback: function(){
var newRecordIndex = e.store.findBy(
function(record, filename) {
if (record.get('filename') === e.record.data.filename) {
return true;
}
return false;
}
);
me.grid.getSelectionModel().select(newRecordIndex);
}
});
}
});
return true;
}
}
});
and place it to your plugin.
I don't try it first, but may be this will help you a little.
AND this is for your controller to add a record from your grid, you need a button to trigger this function.
createRecord: function() {
var model = Ext.ModelMgr.getModel('FM.model.DefineCode');
var r = Ext.ModelManager.create({
id: '',
name: '',
filename: ''
}, model);
this.getYourgrid().getStore().insert(0, r);
this.getYourgrid().rowEditing.startEdit(0, 0);
}
check this for your need, this is look a like. You need to specify the content-type.
And for your java need, please read this method to upload a file.

Removing a record from store in an editable grid

I created an editable grid with local data from Array Store. Now I put an actionColumn to delete the record from the store. But the delete is not happening and the record is still present.
Please see my code below:-
this.empdata = [
[ 'Anea etet','andreeas#jhggf.com','active' ],
[ 'Bharfdna ivasdsh','bfanas#dsgfsd.com','active' ],
[ 'Crfg gfdgdtt', 'ffigh#dfsd.com', 'away' ],
[ 'Gfdgdis Perron','geffgsp#fdhd.com', 'away' ]
];
this.employee = new Ext.data.ArrayStore({
autoSync: true,
fields : [ {
name : 'name'
}, {
name : 'email'
}, {
name : 'status'
}],
data : this.empdata
});
var cm = new Ext.grid.ColumnModel([{
header: 'Name',
dataIndex: 'name',
flex: 1,
editor: {
allowBlank: false
}
}, {
header: 'Email',
dataIndex: 'email',
flex: 1,
editor: {
allowBlank: false,
vtype: 'email'
}
}, {
header: 'Status',
dataIndex: 'status',
editor: {
allowBlank: false
}
}, {
xtype: 'actioncolumn',
width: 50,
items: [
{
icon : 'src/images.jpg',
tooltip: 'Delete record',
handler: function(grid, rowIndex, colIndex) {
var rec = grid.getStore().getAt(rowIndex);
alert("Delete " + rec.get('name'),function(btn,text){
if (btn == 'ok'){
grid.getStore().removeAt(rowIndex);
grid.getStore().sync();
}
})
}
}]
}]);
this.grid = new Ext.grid.EditorGridPanel({
store: this.employee,
cm: cm,
xtype: 'editorgrid',
title: 'Employee Data',
clicksToEdit: 1,
frame: true,
stripeRows : true,
width: 1000,
height: 500,
region: 'south',
viewConfig : {
forceFit : true,
scrollOffset : 0,
}
});
this.grid.on('validateedit', function(e) {
if (e.field === 'status'){
if(!((e.value === 'active')||(e.value === 'away')||(e.value === 'offline'))){
e.cancel = true;
e.record.data[e.field] = e.originalValue;
}
}
});
var win = {
layout: {
type: 'vbox',
align: 'center',
pack: 'top',
padding: 30
},
items: [this.grid]
};
Ext.apply(this, win);
When i click on delete button,a pop-up comes up asking fro confirmation.When I click 'ok' it should delete the record,but nothing happens.
Please suggest what's wrong with the code.
You use alert in yor handler it only accepts one parameter - message. If you want confirm, the best way is to use Ext.Msg.confirm. Example:
handler: function(grid, rowIndex, colIndex) {
var rec = grid.getStore().getAt(rowIndex);
Ext.Msg.confirm(
"Delete " + rec.get('name'),
"Delete " + rec.get('name'),
function(btn){
if (btn == 'yes'){
grid.getStore().removeAt(rowIndex);
grid.getStore().sync();
}
}
);
}

Dojo-DataGrid :: How to dynamically fetch values as options for a select box in Dojo DataGrid

I have a Dojo-DataGrid which is programatically populated as below :
var jsonStore = new dojo.data.ItemFileWriteStore({ url: "json/gaskets.json" });
var layout= [
{ field: "description", width: "auto", name: "Tier/Description", editable:true },
{ field: "billingMethod", width: "auto", name: "Billing Method", editable: true,
type: dojox.grid.cells.Select, options: [ '0', '1' ] },
{ field: "offeringComponents", width: "auto", name: "Offering Component", editable: true,
type: dojox.grid.cells.Select, options: [ '0', '1' ] },
{ field: "serviceActivity", width: "auto", name: "Service Activity", editable: true,
type: dojox.grid.cells.Select, options: [ '0', '1' ] },
{ field: "hours", width: "auto", name: "Hours" },
{ field: "rate", width: "auto", name: "Rate <br/> (EUR)" },
{ field: "cost", width: "auto", name: "Cost <br/> (EUR)" },
{ field: "price", width: "auto", name: "Price <br/> (EUR)" },
{ field: "gvn", width: "auto", name: "Gvn" }
];
grid = new dojox.grid.DataGrid({
query: { description: '*' },
store: jsonStore,
structure: layout,
rowsPerPage: 20
}, 'gridNode');
The options for the field billingMethod (Currently defined as dojox.grid.cells.Select) are hard coded right now, but I would like to get those values dynamically from the backend as JSON. But dojox.grid.cells.Select currently(I am using Dojo 1.5) does not have a option to define a "store".
I am trying to use dijit.form.FilteringSelect, but this needs a id(of a Div) for its constructor and I cannot specify one as this select box has to go with in the grid, rather than a separate DIV.
Thanks
Sandeep
Your answer works fine, the issue is that in the combo the user can select A, but once the combo lose the focus, the value 1 will be shown. Some months ago I had the same problem, and I got a solution from KGF on #dojo. The idea is to have a formatter on the cell that just creates a SPAN element, and then it invokes a query over the store to get the label of the selected element and put it on the SPAN. I modified your example to get that working.
dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dojox.grid.cells.dijit");
dojo.require("dojox.grid.DataGrid");
dojo.require("dijit.form.Select");
dojo.require('dojox.grid.cells.dijit');
dojo.require('dijit.form.FilteringSelect');
var grid;
var jsonStore;
dojo.addOnLoad(function() {
jsonStore = new dojo.data.ItemFileWriteStore({
data: {
"identifier": "identify",
"label": "description",
"items": [
{
"identify": 123,
"description": "Project Manager"},
{
"identify": 234,
"description": "Developer"},
{
"identify": 536,
"description": "Developer",
"billingMethod":2}
]
}
});
var myStore = new dojo.data.ItemFileReadStore({
data: {
identifier: 'value',
label: 'name',
items: [{
value: 1,
name: 'A',
label: 'A'},
{
value: 2,
name: 'B',
label: 'B'},
{
value: 3,
name: 'C',
label: 'C'}]
}
});
//[kgf] callback referenced by formatter for FilteringSelect cell
function displayValue(nodeId, store, attr, item) {
if (item != null) { //if it's null, it wasn't found!
dojo.byId(nodeId).innerHTML = store.getValue(item, attr);
}
}
var layout = [
{
field: "identify",
width: "auto",
name: "Id 2 Hide",
hidden: true},
{
field: "description",
width: "auto",
name: "Tier/Description",
editable: true},
{
field: 'billingMethod',
name: 'Billing Method',
editable: true,
required: true,
width: '150px',
type: dojox.grid.cells._Widget,
widgetClass: dijit.form.FilteringSelect,
widgetProps: {
store: myStore
},
formatter: function(data, rowIndex) { //[kgf]
//alert("data "+data)
var genId = 'title' + rowIndex;
var store = this.widgetProps.store;
var attr = "label";
setTimeout(function() {
store.fetchItemByIdentity({
identity: data,
onItem: dojo.partial(displayValue, genId, store, attr)
});
}, 50);
//for now return a span with a predetermined id for us to populate.
return '<span id="' + genId + '"></span>';
}
}
];
grid = new dojox.grid.DataGrid({
query: {
description: '*'
},
store: jsonStore,
singleClickEdit: true,
structure: layout,
rowsPerPage: 20
}, 'gridNode');
grid.startup();
});
I was finally able to figure this out..Incase someone wants to implement same kind of stuff using DOJO Datagrid+FilteringSelect.
Sample Code
dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dojox.grid.cells.dijit");
dojo.require("dojox.grid.DataGrid");
dojo.require("dijit.form.Select");
dojo.require('dojox.grid.cells.dijit');
dojo.require('dijit.form.FilteringSelect');
var grid;
var jsonStore;
dojo.addOnLoad(function() {
jsonStore = new dojo.data.ItemFileWriteStore({
data: {
"identifier": "identify",
"label": "description",
"items": [
{
"identify": 123,
"description": "Project Manager"},
{
"identify": 234,
"description": "Developer"},
{
"identify": 536,
"description": "Developer"}
]
}
});
var myStore = new dojo.data.ItemFileReadStore({
data: {
identifier: 'value',
label: 'name',
items: [{
value: 1,
name: 'A',
label: 'A'},
{
value: 2,
name: 'B',
label: 'Y'},
{
value: 3,
name: 'C',
label: 'C'}]
}
});
var layout = [
{
field: "identify",
width: "auto",
name: "Id 2 Hide",
hidden: true},
{
field: "description",
width: "auto",
name: "Tier/Description",
editable: true},
{
field: 'billingMethod',
name: 'Billing Method',
editable: true,
required: true,
width: '150px',
type: dojox.grid.cells._Widget,
widgetClass: dijit.form.FilteringSelect,
widgetProps: {
store: myStore
}}
];
grid = new dojox.grid.DataGrid({
query: {
description: '*'
},
store: jsonStore,
singleClickEdit: true,
structure: layout,
rowsPerPage: 20
}, 'gridNode');
grid.startup();
});