Checkbox Selection + Grid Panel with Summary Row in ExtJS 4 - javascript

given the following Grid Panel:
Ext.onReady(function() {
var sm = new Ext.selection.CheckboxModel( {
listeners:{
selectionchange: function(selectionModel, selected, options){
// Bunch of code to update store
}
}
});
var grid = Ext.create('Ext.grid.Panel', {
features: [{
ftype: 'summary'
}],
store: store,
defaults: { // defaults are applied to items, not the container
sortable:true
},
selModel: sm,
columns: [
{header: 'Column 1', flex: 1, dataIndex: 'd1', summaryRenderer: function(value, summaryData, dataIndex) { return "Selected Data"} },
{header: 'C2', width: 150, dataIndex: 'd2', summaryType: 'sum'},
{header: 'C3', width: 150, dataIndex: 'd3', renderer: dRenderer, summaryType: 'sum'},
{header: 'C4', width: 150, dataIndex: 'd4', renderer: dRenderer, summaryType: 'sum'},
{header: 'C5', width: 150, renderer: total, summaryRenderer: grandTotal}
],
width: "100%",
title: 'Grid',
renderTo: 'grid',
viewConfig: {
stripeRows: true
}
});
});
How does this need to be refactored to summarize the data of only those rows that are selected? I know that I probably need to override the sum function of the Summary Feature, but haven't been able to find an example or proper syntax in the docs.
Thanks!
Here was my attempt at a solution (posted on the Sencha 4.x help forum w/ no responses):
Ext.define('Ext.grid.feature.SelectedSummary', {
extend: 'Ext.grid.feature.Summary',
alias: 'feature.selectsummary',
generateSummaryData: function(){
var me = this,
data = {},
store = me.view.store,
selectedRecords = me.view.selModel.selected,
columns = me.view.headerCt.getColumnsForTpl(),
i = 0,
length = columns.length,
fieldData,
key,
comp;
for (i = 0, length = columns.length; i < length; ++i) {
comp = Ext.getCmp(columns[i].id);
val = 0;
for(j = 0, numRecs = selectedRecords.items.length; j < numRecs; j++ ) {
field = columns[i].dataIndex;
rec = selectedRecords.items[j];
console.log(rec.get(field));
val += rec.get(field);
}
data[comp.dataIndex] = val;//me.getSummary(store, comp.summaryType, comp.dataIndex, false);
}
return data;
}
});
But this only renders correctly on initial render and only renders when I step through the code with a debugger. There's some kind of race condition where the row gets rendered without the calculations being completed.
Any ideas? Is my question too specific? Perhaps just simple pointers on writing my own feature and adding it to a Grid Panel.

Solution from a colleague:
The summary feature has the capability to take a function as the summaryType. Because the column config does not get passed to this function by default you need to define a closure that will hold on to the dataIndex.
var sm = new Ext.selection.CheckboxModel( {
listeners:{
selectionchange: function(selectionModel, selected, options){
// Must refresh the view after every selection
myGrid.getView().refresh();
// other code for this listener
}
}
});
var getSelectedSumFn = function(column){
return function(){
var records = myGrid.getSelectionModel().getSelection(),
result = 0;
Ext.each(records, function(record){
result += record.get(column) * 1;
});
return result;
};
}
// create the Grid
var myGrid = Ext.create('Ext.grid.Panel', {
autoScroll:true,
features: [{
ftype: 'summary'
}],
store: myStore,
defaults: { // defaults are applied to items, not the container
sortable:true
},
selModel: sm,
columns: [
{header: 'h0', flex: 1, dataIndex: 'groupValue'},
{header: 'h1', width: 150, dataIndex: 'd1', summaryType: getSelectedSumFn('d1')},
{header: 'h2', width: 150, dataIndex: 'd2', renderer: r, summaryType: getSelectedSumFn('d2')},
{header: 'h3', width: 150, dataIndex: 'd3', renderer: r, summaryType: getSelectedSumFn('d3')},
{header: 'h4', width: 150, dataIndex: 'd4', renderer: r, summaryType: getSelectedSumFn('d4')}
],
width: "100%",
height: "300",
title: 'Data',
renderTo: 'data',
viewConfig: {
stripeRows: true
}
});

A little bit updated previous solution:
var sm = new Ext.selection.CheckboxModel({
listeners: {
selectionchange: function (selectionModel, selected, options) {
// Must refresh the view after every selection
selectionModel.view.refresh();
}
}
});
var getSelectedSumFn = function (column, selModel) {
return function () {
var records = selModel.getSelection(),
result = 0;
Ext.each(records, function (record) {
result += record.get(column) * 1;
});
return result;
};
};
and then in grid use following line:
summaryType: getSelectedSumFn('d4', sm)}

Related

multi column headers iggrid with knockout issue

I am using IgniteUI to place a grid on a site. The grid is bound using KnockoutJS. I've used this setup for many grids in my application, but I've run into a weird issue.
I need to have a grid that has a multi column header, and another column after that. I've used multi column headers and they work fine. In this instance, though, the grid will place the info from the column that should be after the group into the first column of the group, as seen in this fiddle: http://jsfiddle.net/rc5a4vbs/3/. The ColumnY column should have a bunch of Ys in it on both rows, as seen in the Javascript.
function ViewModel() {
var self = this;
self.value = ko.observable(false);
self.data = ko.observableArray([
{ "ColumnA": ko.observable(1), "ColumnD": ko.observable(21), "ColumnE": ko.observable("dkifhugb"),
"ColumnF": ko.observable(true), "ColumnG": ko.observable("false"),
"Procedure": ko.observable("Final Column"),
"TestConditionGroup": {
"ColumnY": ko.observable("YYYYYYYYYYYY"), "ColumnZ": ko.observable("ZZZZZZZZZ")
}
},
{ "ColumnA": ko.observable(2), "ColumnD": ko.observable(14), "ColumnE": ko.observable("5347347"),
"ColumnF": ko.observable(false), "ColumnG": ko.observable("string"),
"Procedure": ko.observable("Final Column"),
"TestConditionGroup": {
"ColumnY": ko.observable("yyyyyyyyyyyy"), "ColumnZ": ko.observable("zzzzzzzzzzz")
}
}
]);
self.getColumns = function() {
//debugger;
var columns = [
{ key: 'ColumnA', headerText: '', width: '0px', hidden: true },
{ key: 'ColumnD', headerText: 'Sequence', width: '100px' },
{ key: 'ColumnE', headerText: 'Iteration', width: '100px' },
{ key: 'ColumnF', headerText: 'Risk', width: '100px' },
{ key: 'ColumnG', headerText: 'Sub-Chapter Title', width: '200px' }
];
var columns2 = [
{ key: 'TestConditionGroup', headerText: 'ColumnY', width: '100px',
formatter: function(val){
return val[this.headerText];
}
},
{ key: 'TestConditionGroup', headerText: 'ColumnZ', width: '100px',
formatter: function(val){
return val[this.headerText];
}
}
];
columns.push({ key: 'TestConditionGroup', headerText: 'Test Conditions', group: columns2 });
columns.push({ key: 'Procedure', headerText: 'Procedure', width: '200px'});
return columns;
}
}
The grid was working correctly until I made the data that is in the grouped columns into an object within the row object. This is how the server will be sending me the info. When all of the columns were on the top level it worked fine.
How can I get the data to appear correctly with this set up for the supplied data? Any help would be greatly appreciated.
The problem is not caused by the Multi-Column Headers, but from the complex object property that you have in your data.
If you want to bind the ColumnY and ColumnZ then you have to declare them as unbound columns and in the formatter function extract their values from the TestConditionGroup property of the data. You do that by using a second parameter in the formatter function which will give you a reference to the current row data.
var columns2 = [
{ key: 'ColumnY', headerText: 'ColumnY', width: '100px', unbound: true,
formatter: function(val, row){
return row["TestConditionGroup"][this.headerText];
}
},
{ key: 'ColumnZ', headerText: 'ColumnZ', width: '100px', unbound: true,
formatter: function(val, row){
return row["TestConditionGroup"][this.headerText];
}
}];
Also to make the data from the TestConditionGroup column available in the formatter functions you have to configure localSchemaTransform to false.
The last thing you need to do is to set the autoGenerateColumns to false, because it's true by default.
Here is the link to the updated fiddle:
http://jsfiddle.net/rc5a4vbs/4/

EnhancedGrid within another EnhancedGrid

I'm using the dojo grid cell formatter to display an inner grid within another grid. Even though the inner grid is added, it does not display on the HTML page cause its height and width are 0px.
My JSP page and the JS page where the grids are created is shown below. Any help will be appreciated.
My guess is that calling grid.startup() in the cell formatter is probably not the right place. But where should I move the startup() call to -or- is there something else that needs to be done to get the inner grid to render correctly.
----JSP file ----
<script type="text/javascript"> dojo.require("portlets.ListPortlet"); var <portlet:namespace/>args = { namespace: '<portlet:namespace/>', listDivId: 'listGrid' }; var <portlet:namespace/>controller = new portlets.ListPortlet(<portlet:namespace/>args); dojo.addOnLoad(function(){ <portlet:namespace/>controller.init(); }); </script>
</div>
----JS file ----
dojo.declare("portlets.ListPortlet", null, {
constructor: function(args){
dojo.mixin(this,args);
this.params = args;
},
init: function(){
var layout = [[
{field: 'site', name: 'Site', width: '30px' }
{field: 'name', name: 'Full Name', width: '100px'},
{field: 'recordStatus', name: 'Status', width: '80px' }
],[
{field: '_item', name: ' ', filterable: false, formatter: this.formatNotesTable, colSpan: 3 }
]];
this.grid = new dojox.grid.EnhancedGrid({
autoHeight: true,
autoWidth: true,
selectable: true,
query:{
fromDate: start,
toDate: end
},
rowsPerPage: 10
});
this.grid.placeAt(dojo.byId(this.listDivId));
this.dataStore = new dojox.data.JsonRestStore({target: dataURL, idAttribute: idAttribute});
this.grid.setStructure(layout);
this.grid.startup();
},
formatNotesTable(rowObj) {
var gridData = {
identifier:"id",
items: [
{id:1, "Name":915,"IpAddress":6},
{id:2, "Name":916,"IpAddress":7}
]
};
var gridStructure = [{
cells:[
[
{ field: "Name",
name: "Name",
},
{ field: "IpAddress",
name: "Ip Address" ,
styles: 'text-align: right;'
}
]
]
}];
var gridStore = new dojo.data.ItemFileReadStore( { data: gridData} );
var cpane = new dijit.layout.ContentPane ({
content: "inner grid should be displayed below"
});
var subgrid = new dojox.grid.DataGrid({
store: gridStore,
structure: gridStructure,
style: {width: "325px", height: "300px"}
});
subgrid.placeAt(cpane);
subgrid.startup();
return cpane;
}
}
I solved my problem by using a dojox.layout.TableContainer inside the EnhancedGrid.

dynamically hide ExtJS 4 grid column when grouping on column

I have an ExtJS 4 gridPanel as below:
var grid = Ext.create('Ext.grid.Panel', {
store: store,
title: 'grid',
columns: [
{text: 'column 1', sortable: true, width: 70, dataIndex: 'column1'},
{text: 'column 2', sortable: true, width: 70, dataIndex: 'column2'},
{text: 'column 3', sortable: true, width: 70, dataIndex: 'column3'},
{text: 'column 4', sortable: true, width: 70, dataIndex: 'column4'},
],
renderTo: Ext.get('gridDiv'),
width: 800,
height: 600,
listeners: {
},
features: [{
ftype: 'grouping'
}]
});
I'm required to dynamically hide the column that the grid is being grouped by whenever the grid is grouped, and show all other columns - reshowing any previously hidden columns.
I understand that this would be a listener handler that catches the grouping changing, which would then fire column.hide().
Some pseudo-code:
...
listeners: {
groupchange: function(store, groupers, eOpts) {
groupers.forEach(function(group) {
grid.columns.forEach(function(column) {
if(column==group)
column.hide();
if(column==group)
column.show();
}
}
}
},
...
I'm not sure from the API documentation whether groupchange is an event that can be caught by the grid, rather than the store, how to access the contents of groupers, and what comparators are available to determine if a column is in groupers.
How should this listener event be structured? What are the correct events/methods/properties to use?
Found that the hiding is done on a store listener, despite the grid panel API making it look as though it can be done as a grid listener. I've worked off the first keys array value within the groupers, although you could just as easily use items[0].property value.
var store = Ext.create('Ext.data.Store', {
...
listeners:
{
groupchange: function(store, groupers, eOpts){
var column = groupers.keys[0];
productionItemGrid.columns.forEach(function(entry){
if(entry.dataIndex == column)
{
entry.setVisible(false);
}
else
{
entry.setVisible(true);
}
});
}
}
...
});

ExtJS - Complex form serialization

I have a complex form which I can't use form serialization technique. There are many fields as well as dynamic grid ( the grid dynamically generating upon user choosing some criteria ) inside the form.
What I want to do, collect user inputs/selections + adding selected records that available in the grid then finally making a JSON array with those datas to be able to post server side.
My guess, I can use getCmp function of the ExtJS to take whole datas but as you might guess this way little bit hard to maintain. Also, I have no idea to get grid data with this way!
PS : Code is little bit long so that I cropped some parts.
MODEL AND STORE DEFINITIONS
Ext.Loader.setConfig({enabled: true});
Ext.Loader.setPath('Ext.ux', '<?php echo js_url(); ?>resources/ux');
Ext.require([
'Ext.grid.*',
'Ext.data.*',
'Ext.form.*',
'Ext.state.*',
'Ext.util.*',
'Ext.layout.container.Column',
'Ext.selection.CheckboxModel',
'Ext.ux.RowExpander',
'Ext.ux.statusbar.StatusBar'
]);
var navigate = function (panel, direction) {
var layout = panel.getLayout();
layout[direction]();
Ext.getCmp('move-prev').setDisabled(!layout.getPrev());
Ext.getCmp('move-next').setDisabled(!layout.getNext());
};
// Article Model
Ext.define('Article', {
extend: 'Ext.data.Model',
fields: [
{name: 'ARTICLE_ID', type: 'int'},
{name: 'DESCRIPTION', type: 'string'}
]
});
// Article Json Store
var articles = new Ext.data.JsonStore({
model: 'Article',
proxy: {
type: 'ajax',
url: '<?php echo base_url() ?>create/get_articles',
reader: {
type: 'json',
root: 'artList',
idProperty: 'ARTICLE_ID'
}
}
});
winArticle = new Ext.Window({
width: 600,
modal: true,
title: 'Artikel Seçimi',
closeAction: 'hide',
bodyPadding: 10,
items: new Ext.Panel({
items: [
{
xtype: 'fieldset',
title: 'Artikel Sorgulama',
defaultType: 'textfield',
layout: 'anchor',
defaults: {
anchor: '100%'
},
height: '76px',
items: [
{
xtype: 'fieldcontainer',
layout: 'hbox',
defaultType: 'textfield',
items: [
{
xtype: 'combobox',
id: 'articleNo',
inputWidth: 320,
fieldLabel: 'ARTİKEL NO',
fieldStyle: 'height: 26px',
margin: '10 15 0 0',
triggerAction: 'query',
pageSize: true
},
{
xtype: 'button',
text: 'SORGULA',
width: 100,
scale: 'medium',
margin: '8 0 0 0'
}
]
}
]
},
{
xtype: 'fieldset',
title: 'Artikel Bilgileri',
height: '140px',
layout: 'fit',
items: [
{
xtype: 'fieldcontainer',
layout: 'hbox',
defaultType: 'textfield',
fieldDefaults: {
labelAlign: 'top'
},
items: [
{
fieldLabel: 'ARTİKEL TANIMI',
name: 'artDesc',
flex: 3,
margins: '0 5 0 0'
},
{
fieldLabel: 'PAKET İÇERİĞİ',
name: 'artgebi',
flex: 1
}
]
},
{
xtype: 'fieldcontainer',
layout: 'hbox',
defaultType: 'textfield',
id: 'artContainer1',
fieldDefaults: {
labelAlign: 'top'
},
items: [
{
fieldLabel: 'SUBSYS',
name: 'artSubsys',
flex: 1,
margins: '0 5 0 0'
},
{
fieldLabel: 'VARIANT',
name: 'artVariant',
flex: 1,
margins: '0 5 0 0'
},
{
fieldLabel: 'VARIANT TANIMI',
name: 'artVariantDesc',
flex: 2
}
]
}
]
},
{
xtype: 'fieldset',
title: 'Aksiyon Seviyeleri',
id: 'article-fieldset',
items: [
{
xtype: 'button',
id: 'btnArticleLevelAdd',
text: 'LEVEL EKLE',
scale: 'medium',
width: 100,
style: 'float: right',
margin: '0 7 0 0',
handler: function() {
var getLevels = function() {
var count = winArticle.down('fieldset[id=article-fieldset]').items.items.length;
return count;
}
var count = getLevels();
if (count === 3) {
Ext.getCmp('btnArticleLevelAdd').disable();
}
var container = 'artContainer' + count;
//console.log(container);
Ext.getCmp('article-fieldset').add([
{
xtype: 'fieldcontainer',
layout: 'hbox',
id: 'artContainer' + count,
defaultType: 'textfield',
fieldDefaults: {
labelAlign: 'top'
},
items: [
{
name: 'artLevel' + count,
allowBlank: false,
inputWidth: 216,
fieldStyle: 'text-align: right; font-size: 13pt; background-color: #EAFFCC;',
margins: '0 5 5 0'
},
{
name: 'artValue' + count,
allowBlank: false,
inputWidth: 216,
fieldStyle: 'text-align: right; font-size: 13pt; background-color: #EAFFCC;',
margins: '0 5 0 0'
},
{
xtype: 'button',
text: 'SİL',
width: 40,
cls: 'btn-article-remove',
handler: function() {
if(count <= 3) {
Ext.getCmp('btnArticleLevelAdd').enable();
} else {
Ext.getCmp('btnArticleLevelAdd').disable();
}
winArticle.down('fieldset[id=article-fieldset]').remove(container);
}
}
]
}
]);
}
},
{
xtype: 'fieldcontainer',
layout: 'hbox',
id: 'article-level-container',
defaultType: 'textfield',
fieldDefaults: {
labelAlign: 'top'
},
items: [
{
fieldLabel: 'LEVEL',
name: 'artLevel',
inputWidth: 216,
margins: '0 5 5 0',
allowBlank: false,
fieldStyle: 'text-align: right; font-size: 13pt; background-color: #EAFFCC;'
},
{
fieldLabel: 'VALUE',
name: 'artValue',
inputWidth: 216,
allowBlank: false,
blankText: 'zorunlu alan, boş bırakılamaz',
fieldStyle: 'text-align: right; font-size: 13pt; background-color: #EAFFCC;',
listeners: {
change: function(textfield, newValue, oldValue) {
if(oldValue == 'undefined' || newValue == '') {
Ext.getCmp('btnArticleSave').disable();
} else {
Ext.getCmp('btnArticleSave').enable();
}
}
}
}
]
}
]
}
]
}),
buttons: [
{
text: 'KAPAT',
scale: 'medium',
width: 100,
cls: 'btn-article-close',
listeners: {
click: function() {
winArticle.close();
}
}
},
'->',
{
text: 'EKLE',
scale: 'medium',
disabled: true,
width: 100,
margin: '0 9 0 0',
cls: 'btn-article-save',
id: 'btnArticleSave'
}
]
});
EXT.ONREADY FUNCTION
Ext.onReady(function () {
Ext.QuickTips.init();
Ext.state.Manager.setProvider(new Ext.state.CookieProvider({
expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 7))
}));
var Discounts = Ext.create('Ext.form.Panel', {
id: 'discount-types',
bodyPadding: 10,
width: 760,
height: 600,
title: 'DNR TANIMLAMA / SCREEN 0',
layout: 'card',
bodyStyle: 'padding:20px',
defaults: {
border: false,
anchor: '100%'
},
style: {
'box-shadow': '0 2px 5px rgba(0, 0, 0, 0.6)',
'-webkit-box-shadow': '0 0 8px rgba(0, 0, 0, 0.5)'
},
frame: true,
buttons: [
{
text: 'ÖNCEKİ ADIM',
id: 'move-prev',
cls: 'np-button',
scale: 'medium',
iconCls: 'dnr-prev-icon',
iconAlign: 'left',
handler: function (btn) {
navigate(btn.up('panel'), 'prev');
var itemd = Discounts.getLayout().getActiveItem();
Discounts.setTitle('DNR TANIMLAMA ' + ' / ' + itemd.cardTitle);
Ext.getCmp('dnr-submit').disable();
Ext.getCmp('dnr-submit').setVisible(false);
},
disabled: true
},
{
text: 'SONRAKİ ADIM',
id: 'move-next',
scale: 'medium',
cls: 'np-button',
iconCls: 'dnr-next-icon',
iconAlign: 'right',
handler: function (btn) {
navigate(btn.up('panel'), 'next');
var itemd = Discounts.getLayout().getActiveItem();
Discounts.setTitle('DNR TANIMLAMA ' + ' / ' + itemd.cardTitle);
var cardNum = Discounts.items.indexOf(itemd);
if (cardNum == 3) {
Ext.getCmp('dnr-submit').enable();
Ext.getCmp('dnr-submit').setVisible(true);
}
},
disabled: true
},
'->',
{
text: '&nbsp KAYDET ',
id: 'dnr-submit',
scale: 'medium',
iconCls: 'dnr-submit-icon',
iconAlign: 'right',
cls: 'dnr-submit',
disabled: true,
hidden: true,
handler: function (btn) {
}
}
],
items: [
{
id: 'screen-0',
cardTitle: 'SCREEN 0',
layout: 'form',
items: [
{
layout: {
type: 'vbox',
align: 'center'
},
margin: '60 0 0 0',
items: [
{
xtype: 'combobox',
inputWidth: 295,
fieldLabel: 'DNR TİPİ',
fieldStyle: 'height: 26px',
id: 'discount-type',
store: discounts,
valueField: 'DNR_TYPE_ID',
displayField: 'DNR_TYPE_DESC',
queryMode: 'remote',
forceSelection: true,
stateful: true,
stateId: 'cmb_disc_type',
allowBlank: false,
emptyText: 'DNR tipini seçiniz...',
triggerAction: 'all',
listeners: {
select: function (e) {
var discType = Ext.getCmp('discount-type').getValue();
var discDetail = Ext.getCmp('discount-detail');
discdetails.removeAll();
if (discType != 0) {
discDetail.setDisabled(false);
discdetails.proxy.extraParams = { 'dnrtype': discType };
discdetails.load();
}
}
}
},
{
xtype: 'combobox',
inputWidth: 400,
fieldStyle: 'height: 26px',
id: 'discount-detail',
valueField: 'ID',
displayField: 'DNR_TITLE',
store: discdetails,
forceSelection: true,
stateful: true,
stateId: 'cmb_disc_detail',
margin: '25 0 0 0',
disabled: true,
allowBlank: false,
msgTarget: 'side',
emptyText: 'İNDİRİM TİPİNİ SEÇİNİZ...',
blankText: 'İndirim tipi boş olamaz!',
triggerAction: 'all',
listeners: {
select: function (e) {
var discDetail = Ext.getCmp('discount-detail').getValue();
if (discDetail != 'null') {
var value = discdetails.getAt(discdetails.find('ID', discDetail)).get('DNR_DESCRIPTION');
Ext.getCmp('dnr-type-desc-panel').setVisible(true);
Ext.getCmp('dnr-type-desc-panel').update(value);
}
}
}
},
{
xtype: 'textarea',
grow: false,
name: 'invoiceText',
fieldLabel: 'FATURA METNİ',
id: 'invoice-text',
blankText: 'Fatura metni boş olamaz!',
width: 400,
height: 60,
margin: '30 0 0 0',
allowBlank: false,
msgTarget: 'side',
listeners: {
change: function (e) {
if (Ext.getCmp('invoice-text').getValue().length === 0) {
Ext.getCmp('move-next').disable();
} else {
Ext.getCmp('move-next').enable();
}
}
}
},
{
xtype: 'panel',
id: 'dnr-type-desc-panel',
layout: {type: 'hbox', align: 'stretch'},
height: 145,
width: 400,
cls: 'dnr-desc-panel',
margin: '60 0 0 0',
html: '&nbsp',
hidden: true
}
]
}
]
},
{
id: 'screen-1',
cardTitle: 'SCREEN 1',
layout: 'form',
items: [
{
layout: 'column',
width: 730,
height: 90,
items: [
{
xtype: 'fieldset',
title: 'ARTİKEL / HEDEF GRUP / MAL GRUBU SEÇİMİ',
cls: 'dnr-fieldset',
width: 730,
height: 80,
margin: '0',
items: [
{
xtype: 'buttongroup',
columns: 5,
columnWidth: 140,
frame: false,
margin: '5 0 0 18',
items: [
{
text: 'ARTİKEL',
scale: 'medium',
margin: '0 18px 0 0',
width: 120,
height: 36,
id: 'btn-article',
cls: 'btn-grp-choose btn-grp-article',
listeners: {
click: function () {
winArticle.center();
winArticle.show();
}
}
},
{
text: 'PUAR',
scale: 'medium',
margin: '0 18px 0 0',
width: 120,
height: 36,
cls: 'btn-grp-choose btn-grp-puar',
listeners: {
click: function() {
winPuar.show();
}
}
},
{
text: 'MAL GRUBU',
scale: 'medium',
margin: '0 18px 0 0',
width: 120,
height: 36,
cls: 'btn-grp-choose btn-grp-choose',
listeners: {
click: function() {
winArticleGroup.show();
}
}
},
{
text: 'HEDEF GRUP',
scale: 'medium',
margin: '0 18px 0 0',
width: 120,
height: 36,
cls: 'btn-grp-choose btn-grp-target',
listeners: {
click: function() {
winTargetGroup.show();
}
}
},
{
text: 'SUPPLIER',
scale: 'medium',
width: 120,
height: 36,
cls: 'btn-grp-choose btn-grp-supplier',
listeners: {
click: function() {
winSupplier.show();
}
}
}
]
}
]
}
]
},
{
xtype: 'gridpanel',
id: 'article-grid',
selType: 'rowmodel',
elStatus: true,
plugins: [
{ ptype: 'cellediting', clicksToEdit: 1},
{ ptype: 'datadrop'}
],
/* ***************************************************************
* here is the tricky part! when user change any fields above
* this grid will dynamically generate upon user request. So that
* we arent sure which columns will be available.
* ***************************************************************/
columns: [
{
text: 'COLUMN A',
dataIndex: ''
}
]
}
]
},
renderTo: 'content'
})
});
Updated answer
After some clarification I think the answer should be quite easy (at least I think so) For the following answer I assume that you are inside the form at the time you want to fetch the form & grid data and that there is only one Ext.form.Panel:
// Navigate up to the form:
var form = this.up('form'),
// get the form values
data = form.getValues(),
// get the selected record from the grid
gridRecords = form.down('grid').getSelectionModel().getSelected(),
// some helper variables
len = gridRecords.length,
recordData = [];
// normalize the model data by copying just the data objects into the array
for(i=0;i<len;i++) {
recordData .push(gridRecords[i].data);
}
// apply the selected grid records to the formdata. For that you will need a property name, I will use just 'gridRecords' but you may change it
data.gridRecords = recordData;
// send all back via a ajax request
Ext.Ajax.request({
url: 'demo/sample',
success: function(response, opts) {
// your handler
},
failure: function(response, opts) {
// your handler
},
jsonData: data
});
That should it be
To provide some more options of data that can be fetched from/by the grid
// get all data that is currently in the store
form.down('grid').getStore().data.items
// get all new and updated records
form.down('grid').getStore().getModifiedRecords()
// get all new records
form.down('grid').getStore().getNewRecords()
// get all updated records
form.down('grid').getStore().getUpdatedRecords()
Old answer (for more complex scenarios) below
What you told:
You have a grid with forms and maybe grids. Where you need to also
readout the grids when fetching the data from the form.
In the answer below I will just cover getValues, binding/unbinding events to each grid and not
form load/submit
record load/update
setting values
My recommendation is to make your form much more intelligent so that it is capable of handling this.
What do I mean by?
A default form cares about all fields that are inserted anywhere in it's body. In 99,9% this is perfectly fine but not for all. Your form also need to take care about grids that get inserted.
How it can be done
First thing is that when you make your Grids parts of a form I recommend to give them a name property. Second is that you need to know how a form gather and utilizes the fields so that you be able to copy that for grids. For that you need to take a look at the Ext.form.Basic class constructor where the important part is this
// We use the monitor here as opposed to event bubbling. The problem with bubbling is it doesn't
// let us react to items being added/remove at different places in the hierarchy which may have an
// impact on the dirty/valid state.
me.monitor = new Ext.container.Monitor({
selector: '[isFormField]',
scope: me,
addHandler: me.onFieldAdd,
removeHandler: me.onFieldRemove
});
me.monitor.bind(owner);
What happens here is that a monitor get initialized that from this on will look for any field that get inserted into the bound componenent where the monitor will call the appropriate handler. Currently the monitor is looking for fields but you will need one that is looking for grids. Such a monitor would look like:
me.gridMonitor = new Ext.container.Monitor({
selector: 'grid',
scope: me,
addHandler: me.onGridAdd,
removeHandler: me.onGridRemove
});
me.gridMonitor.bind(owner);
Because I don't know much about your datastructure I cannot tell you which gridevents you might need but you should register/unregister them in the addHandler/removeHandler like
onGridAdd: function(grid) {
var me = this;
me.mon(grid,'select',me.yourHandler,me);
},
onGridRemove: function(grid) {
var me = this;
me.mun(grid,'select',me.yourHandler,me);
}
In addition you will need the following helper methods
/**
* Return all the {#link Ext.grid.Panel} components in the owner container.
* #return {Ext.util.MixedCollection} Collection of the Grid objects
*/
getGrids: function() {
return this.gridMonitor.getItems();
},
/**
* Find a specific {#link Ext.grid.Panel} in this form by id or name.
* #param {String} id The value to search for (specify either a {#link Ext.Component#id id} or
* {#link Ext.grid.Panel name }).
* #return {Ext.grid.Panel} The first matching grid, or `null` if none was found.
*/
findGrid: function(id) {
return this.getGrids().findBy(function(f) {
return f.id === id || f.name === id;
});
},
And most important the method that get's the data from the grids. Here we need to override
getValues: function(asString, dirtyOnly, includeEmptyText, useDataValues) {
var values = {},
fields = this.getFields().items,
grids = this.getGrids().items, // the grids found by the monitor
f,
fLen = fields.length,
gLen = grids.length, // gridcount
isArray = Ext.isArray,
grid, gridData, gridStore, // some vars used while reading the grid content
field, data, val, bucket, name;
for (f = 0; f < fLen; f++) {
field = fields[f];
if (!dirtyOnly || field.isDirty()) {
data = field[useDataValues ? 'getModelData' : 'getSubmitData'](includeEmptyText);
if (Ext.isObject(data)) {
for (name in data) {
if (data.hasOwnProperty(name)) {
val = data[name];
if (includeEmptyText && val === '') {
val = field.emptyText || '';
}
if (values.hasOwnProperty(name)) {
bucket = values[name];
if (!isArray(bucket)) {
bucket = values[name] = [bucket];
}
if (isArray(val)) {
values[name] = bucket.concat(val);
} else {
bucket.push(val);
}
} else {
values[name] = val;
}
}
}
}
}
}
// begin new part
for (g = 0; g < gLen; g++) {
grid = grids[f];
gridStore = grid.getStore();
gridData = [];
// You will need a identification variable to determine which data should be taken from the grid. Currently this demo implement three options
// 0 only selected
// 1 complete data within the store
// 2 only modified records (this can be splitted to new and updated)
var ditems = grid.submitData === 0 ? grid.getSelectionModel().getSelection() :
grid.submitData === 1 ? gridStore.getStore().data.items : gridStore.getStore().getModifiedRecords(),
dlen = ditems.length;
for(d = 0; d < dLen; d++) {
// push the model data to the current data list. It doesn't matter of which type the models (records) are, this will simply read the whole known data. Alternatively you may access the rawdata property if the reader does not know all fields.
gridData.push(ditems[d].data);
}
// assign the array of record data to the grid-name property
data[grid.name] = gridData;
}
// end new part
if (asString) {
values = Ext.Object.toQueryString(values);
}
return values;
}
Clued together should it look something like
Ext.define('Ext.ux.form.Basic', {
extend: 'Ext.form.Basic',
/**
* Creates new form.
* #param {Ext.container.Container} owner The component that is the container for the form, usually a {#link Ext.form.Panel}
* #param {Object} config Configuration options. These are normally specified in the config to the
* {#link Ext.form.Panel} constructor, which passes them along to the BasicForm automatically.
*/
constructor: function(owner, config) {
var me = this;
me.callParent(arguments);
// We use the monitor here as opposed to event bubbling. The problem with bubbling is it doesn't
// let us react to items being added/remove at different places in the hierarchy which may have an
// impact on the dirty/valid state.
me.gridMonitor = new Ext.container.Monitor({
selector: 'grid',
scope: me,
addHandler: me.onGridAdd,
removeHandler: me.onGridRemove
});
me.gridMonitor.bind(owner);
},
onGridAdd: function(grid) {
var me = this;
me.mon(grid,'select',me.yourHandler,me);
},
onGridRemove: function(grid) {
var me = this;
me.mun(grid,'select',me.yourHandler,me);
},
/**
* Return all the {#link Ext.grid.Panel} components in the owner container.
* #return {Ext.util.MixedCollection} Collection of the Grid objects
*/
getGrids: function() {
return this.gridMonitor.getItems();
},
/**
* Find a specific {#link Ext.grid.Panel} in this form by id or name.
* #param {String} id The value to search for (specify either a {#link Ext.Component#id id} or
* {#link Ext.grid.Panel name }).
* #return {Ext.grid.Panel} The first matching grid, or `null` if none was found.
*/
findGrid: function(id) {
return this.getGrids().findBy(function(f) {
return f.id === id || f.name === id;
});
},
getValues: function(asString, dirtyOnly, includeEmptyText, useDataValues) {
var values = {},
fields = this.getFields().items,
grids = this.getGrids().items, // the grids found by the monitor
f,
fLen = fields.length,
gLen = grids.length, // gridcount
isArray = Ext.isArray,
grid, gridData, gridStore, // some vars used while reading the grid content
field, data, val, bucket, name;
for (f = 0; f < fLen; f++) {
field = fields[f];
if (!dirtyOnly || field.isDirty()) {
data = field[useDataValues ? 'getModelData' : 'getSubmitData'](includeEmptyText);
if (Ext.isObject(data)) {
for (name in data) {
if (data.hasOwnProperty(name)) {
val = data[name];
if (includeEmptyText && val === '') {
val = field.emptyText || '';
}
if (values.hasOwnProperty(name)) {
bucket = values[name];
if (!isArray(bucket)) {
bucket = values[name] = [bucket];
}
if (isArray(val)) {
values[name] = bucket.concat(val);
} else {
bucket.push(val);
}
} else {
values[name] = val;
}
}
}
}
}
}
// begin new part
for (g = 0; g < gLen; g++) {
grid = grids[f];
gridStore = grid.getStore();
gridData = [];
// You will need a identification variable to determine which data should be taken from the grid. Currently this demo implement three options
// 0 only selected
// 1 complete data within the store
// 2 only modified records (this can be splitted to new and updated)
var ditems = grid.submitData === 0 ? grid.getSelectionModel().getSelection() :
grid.submitData === 1 ? gridStore.getStore().data.items : gridStore.getStore().getModifiedRecords(),
dlen = ditems.length;
for(d = 0; d < dLen; d++) {
// push the model data to the current data list. It doesn't matter of which type the models (records) are, this will simply read the whole known data. Alternatively you may access the rawdata property if the reader does not know all fields.
gridData.push(ditems[d].data);
}
// add the store data as array to the grid-name property
data[grid.name] = gridData;
}
// end new part
if (asString) {
values = Ext.Object.toQueryString(values);
}
return values;
}
});
Next is to modify the form to use this basic form type
Ext.define('Ext.ux.form.Panel', {
extend:'Ext.form.Panel',
requires: ['Ext.ux.form.Basic'],
/**
* #private
*/
createForm: function() {
var cfg = {},
props = this.basicFormConfigs,
len = props.length,
i = 0,
prop;
for (; i < len; ++i) {
prop = props[i];
cfg[prop] = this[prop];
}
return new Ext.ux.form.Basic(this, cfg);
}
});
Note:
This is all untested! I've done something similar for various
customers to extend the capabilities of forms and I can tell tell that
this way will work very well and fast. At least it should show how it can be done and it can easily be tweaked to also set forms and/or load/update records.
I have not used this myself, but there is a thread that tries to deal with associated models via hasMany relationship. The problem is that everyone has slightly different expectations of what should happen during write operation of records. Serever side ORMs deal with this issue in somewhat difficult to understand manner and is often a sore spot for new developers.
Here is the forum thread that details a custom JSON writer to persist a parent record with it's children records.
Here is the code that seems to work at least for some folks:
Ext.data.writer.Json.override({
/*
* This function overrides the default implementation of json writer. Any hasMany relationships will be submitted
* as nested objects. When preparing the data, only children which have been newly created, modified or marked for
* deletion will be added. To do this, a depth first bottom -> up recursive technique was used.
*/
getRecordData: function(record) {
//Setup variables
var me = this, i, association, childStore, data = record.data;
//Iterate over all the hasMany associations
for (i = 0; i < record.associations.length; i++) {
association = record.associations.get(i);
data[association.name] = null;
childStore = record[association.storeName];
//Iterate over all the children in the current association
childStore.each(function(childRecord) {
if (!data[association.name]){
data[association.name] = [];
}
//Recursively get the record data for children (depth first)
var childData = this.getRecordData.call(this, childRecord);
/*
* If the child was marked dirty or phantom it must be added. If there was data returned that was neither
* dirty or phantom, this means that the depth first recursion has detected that it has a child which is
* either dirty or phantom. For this child to be put into the prepared data, it's parents must be in place whether
* they were modified or not.
*/
if (childRecord.dirty | childRecord.phantom | (childData != null)){
data[association.name].push(childData);
record.setDirty();
}
}, me);
/*
* Iterate over all the removed records and add them to the preparedData. Set a flag on them to show that
* they are to be deleted
*/
Ext.each(childStore.removed, function(removedChildRecord) {
//Set a flag here to identify removed records
removedChildRecord.set('forDeletion', true);
var removedChildData = this.getRecordData.call(this, removedChildRecord);
data[association.name].push(removedChildData);
record.setDirty();
}, me);
}
//Only return data if it was dirty, new or marked for deletion.
if (record.dirty | record.phantom | record.get('forDeletion')){
return data;
}
}
});
The full thread is located here:
http://www.sencha.com/forum/showthread.php?141957-Saving-objects-that-are-linked-hasMany-relation-with-a-single-Store/page5

Hot to disable row selection in Ext.JS grid

How do I disable row selection in an Ext.JS grid?
You must set disableSelection property to true. Its value is ignored if a SelectionModel is specified.
For example:
var grid = new Ext.grid.GridPanel({
disableSelection: true,
store: new Ext.data.Store({
reader: reader,
data: xg.dummyData
}),
columns: [
{id:'company', header: "Company", width: 200, sortable: true, dataIndex: 'company'},
{header: "Price", width: 120, sortable: true, renderer: Ext.util.Format.usMoney, dataIndex: 'price'},
{header: "Change", width: 120, sortable: true, dataIndex: 'change'},
{header: "% Change", width: 120, sortable: true, dataIndex: 'pctChange'},
{header: "Last Updated", width: 135, sortable: true, renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'lastChange'}
],
viewConfig: {
forceFit: true,
// Return CSS class to apply to rows depending upon data values
getRowClass: function(record, index) {
var c = record.get('change');
if (c < 0) {
return 'price-fall';
} else if (c > 0) {
return 'price-rise';
}
}
},
width:600,
height:300,
frame:true,
title:'Framed with Checkbox Selection and Horizontal Scrolling',
iconCls:'icon-grid'
});
If you want to disable selection of some rows only, you can add a listener to the SelectionModel "beforerowselect" event and return false when you don't want a row to be selected.
use this config if you don't have a selection model for you grid
var grid = new Ext.grid.GridPanel({
disableSelection: true,
});
else you this little trick to disable selection in the RowSelectionModel
var grid = new Ext.grid.GridPanel({
selModel : new Ext.grid.RowSelectionModel({selectRow: Ext.emptyFn})
});
you can do another trick for your grid, looks like this :
grid.getSelectionModel().lock();

Categories

Resources