Add filter to a Extjs grid - javascript

I want to add some filters to my grid when I clicked on the filter button (see below).The filters must be add tot the grid with the given values from the filterpanel form.
On this page the textfield will be filled in and when I clicked on the filter button the onFilterClick handler will trigger the FilterController.
Ext.define('path.to.filterPanel', {
extend: 'Ext.form.Panel',
xtype: 'filter',
controller: 'dashboard-filter',
viewModel: {
type: 'dashboard-filter'
},
frame: false,
bodyPadding: 10,
layout: 'form',
// the fields
items: [{
xtype: 'textfield',
name: 'firstName',
id: 'firstName',
fieldLabel: 'Firstname'
}, {
xtype: 'textfield',
name: 'lastName',
id: 'lastName',
fieldLabel: 'Lastname'
}],
buttons: [
text : 'Filter',
handler: 'onFilterClick' // trigger to the controller
}]
});
When clicked on the Filterbutton the values will be pust to this controller.
Ext.define('path.to.FilterController', {
extend: 'Ext.app.ViewController',
alias: 'controller.dashboard-filter',
onFilterClick: function(button) {
var form = button.up('form').getForm();
if (form.isValid()) {
// form valid
var firstName = Ext.getCmp("firstName").getValue();
var lastName = Ext.getCmp("lastName").getValue();
// check if there is some input
if (!!employeeNumber || !!firstName || !!lastName) {
// add filters but how??
}
} else {
// form not valid
console.log("not valid");
}
}
});
Finally this is the grid file where the filters must be added.
Ext.define('path.to.gridPanel, {
extend: 'Ext.grid.Panel',
requires: [
'Ext.grid.column.Action',
'App.store.Employees'
],
controller: 'dashboard-gridVieuw',
xtype: 'gridVieuw',
store: 'Employees',
stateful: true,
collapsible: true,
multiSelect: true,
stateId: 'gridController',
initComponent: function () {
this.store = new App.store.Employees();
var me = this;
me.columns = [{
header : 'Firstname',
flex : 1,
sortable : true,
dataIndex: 'firstName'
}, {
header : 'Lastname',
flex : 1,
sortable : true,
dataIndex: 'lastName'
}]
me.callParent();
}
});
I use version 5 of extjs.

You can use filterBy method to filter the underlying store associated with the grid. Here is an example:
Ext.getStore('myStore').filterBy(function(record, id) {
if (record.get('firstName') === firstName) {
return true;
} else {
return false;
}
});
Here is a fiddle demonstrating a working example of a filter

Thanks for answering my question. It works for me. I've added the follow OnClick handler in the controller.
onFilterClick: function(button) {
var form = button.up('form').getForm();
if (form.isValid()) {
var fieldOne = Ext.getCmp("fieldOne").getValue();
var fieldTwo = Ext.getCmp("fieldTwo").getValue();
// check if there is some input
if (!!fieldOne || !!fieldTwo) {
// get store
var store = Ext.data.StoreManager.lookup('store');
// check if store not empty
if(!Ext.isEmpty(store)){
// clear filters and add a few new filters if params not empty
store.clearFilter(true);
if (!Ext.isEmpty(fieldOne)) {
store.filter("fieldOne", fieldOne)
}
if (!Ext.isEmpty(fieldTwo)) {
store.filter("fieldTwo", fieldTwo)
}
// count the filtered rows
var count = store.snapshot ? store.snapshot.length : store.getCount();
if (count == 0) {
alert("No data found!");
store.clearFilter();
}
} else{
//Store empty
console.warn("Store's empty");
}
} else {
// no values
alert("No entered data!");
}
} else {
// form not valid
alert("Form not valid!");
}
}

Related

The problem with getting the top container component. Extjs

When I click on a tree record, I try to set the values ​​of this record and set these values ​​in the form.
In the eventcler itemclick: this.showDataFields function is triggered:
....
showDataFields: function(view, record, item, index, event) {
//got a form with fields
var panel = view.up('maintab');
console.log(panel)
//var formfield = panel.down('actionform');
//assign values from selected record to form fields
//formfield.loadRecord(record);
},
..........
In this function, view.up ('maintab') is underfined.
The maintab is Ext.tab.Panel which houses the tree.
Why can not get the topmost container and how to do it correctly?
Made an example in fiddle
thank
You should use view.up('treepanel').nextSibling().getForm().setValues(record.data) in your showDataFields function to set these values ​​in the form.
You could have provided a better example, therefore within the limitations that were proposed.
The answer I got was this were the changes in the ActionFormTree class that got the code below:
Ext.define('Fiddle.view.ActionFormTree', {
extend: 'Ext.form.Panel',
alias: 'widget.actionformtree',
xtype: 'actionform',//mainform,
initComponent: function(){
var me = this;
Ext.apply(me,{
items: [{
xtype: 'form',
border: false,
anchor: '100%',
height: 100,
layout: {
type: 'vbox',
align: 'middle',
pack: 'center'
},
items: [{
xtype: 'textfield',
name: 'text',
fieldLabel: 'Наименование',
itemId: 'name_field',
}, {
xtype: 'textfield',
name: 'code',
fieldLabel: 'Код',
itemId: 'code_field',
}]
}],
buttons: [{
text: 'Save Changes',
scope: me,
handler: function (button) {
//Эта панель со значениями полей
form = me.down('form');
var mainpanel = me.up('#maincontainer');
var treeform = mainpanel.down('usertree');
var sel = treeform.getSelectionModel().getSelection()[0];
store = treeform.getStore();
console.log(treeform)
store.suspendAutoSync()
var child = sel.set({
text: 'Измененное',
leaf: true
});
sel.expand()
store.resumeAutoSync();
//var currRecord = form.getRecord();
//if (currRecord) {
// form.updateRecord();
// form.reset();
//}
}
}]
});
me.callParent(arguments);
}
});
So, in this example, for it to work, you will need to have a node selected to work.
Hope it helps and finalize your question.
Sample to your code

Bind in button not working in Ext JS

I want the Zulu button to be disabled until the item inside the change function has a newVal set to it. Currently the Zulu button is enabled and this is an issue because I want it to be disabled until a certain condition, ie. item.set('textstuff', newVal); is met.
What is wrong with my code? I used this post: ExtJS 6 - Bind disabled property to new records in a store for some inspiration but still need some help.
title: 'Foo',
xtype: 'Bar',
autoSelect: true,
labelWidth: 150,
listeners: {
change: function(component, newVal, OldVal) {
var view = this.up('uploadthings');
var items = view.getViewModel().getStore('things').data.items;
items.forEach(function(item) {
item.set('textstuff', newVal);
});
view.getViewModel('bindBool', true);
}
}
}, {
items: [{
xtype: 'panel',
buttons: [{
style: 'margin-right: 30px',
text: 'Zulu',
iconCls: 'x-fa fa-upload',
handler: 'xray',
bind: {
disabled: '{bindBool}'
}
}]
}]
or in your ViewModel.Js file you can add formulas and configure your bondbool,
lets say you set the bindbool at the controller : me.getViewModel().set('bindbool', true)
in your ViewModel :
formulas : {
bindbool : {
get : function(get){
var tempVar = get('bindbool'); //--> true because you set it to true
return tempVar == true ? tempVar : false;
}
}
}
By doing this you can control your viewModel outputs,
Goodluck and have fun coding Extjs

Why ui-grid reset to default state, after set filter, after restore state?

I'll created ui-grid and make functionality to save grid state to cookies via localStorageService. Then I change column width and save this state. After I restore state via 'gridApi.saveState.restore' and this do is perfect, but when I set filter, grid reset column to default width.
Please tell Me if I do something wrong.
$scope.enableFiltering = function () {
var isEnabledFiltering = localStorageService.get('enableFiltering');
if (!_.isNull(isEnabledFiltering) && !_.isUndefined(isEnabledFiltering)) {
return JSON.parse(isEnabledFiltering);
}
return false;
};
$scope.colDefs = [
{
displayName: locMsg['id'],
field: 'id',
enableHiding: true,
visible: false,
headerCellClass: 'header-filtered',
filters: [{
condition: uiGridConstants.filter.CONTAINS
}]
},
{
displayName: locMsg['name'],
field: 'name',
enableHiding: true,
headerCellClass: 'header-filtered',
filters: [{
condition: uiGridConstants.filter.CONTAINS
}],
},];
$scope.regularGridStateName = "grid";
$scope.defaultGridStateName = "defaultGrid";
$scope.gridOptions = {
enableFiltering: $scope.enableFiltering(),
enableGridMenu: true,
columnDefs : $scope.colDefs
};
$scope.toggleFiltering = function () {
$scope.gridOptions.enableFiltering = !$scope.gridOptions.enableFiltering;
localStorageService.set('enableFiltering', $scope.gridOptions.enableFiltering);
$scope.gridApi.core.notifyDataChange(uiGridConstants.dataChange.COLUMN);
var gridState = localStorageService.get($scope.regularGridStateName);
if (gridState) {
gridApi.saveState.restore($scope, gridState);
}
};
$scope.gridOptions.onRegisterApi = function (gridApi) {
$scope.gridApi = gridApi;
$scope.gridOptions.gridMenuCustomItems.push({
title: 'Reset table',
action: function () {
var defaultState = localStorageService.get($scope.defaultGridStateName);
localStorageService.set($scope.regularGridStateName, defaultState);
if (defaultState) {
gridApi.saveState.restore($scope, defaultState);
}
},
order: 220
});
$scope.gridOptions.gridMenuCustomItems.push({
title: 'Save table state',
action: function () {
localStorageService.set($scope.regularGridStateName, $scope.gridApi.saveState.save());
},
order: 221
});
$timeout(function () {
gridStateService.saveDefaultStateIfNotExist($scope.defaultGridStateName, $scope.gridApi.saveState.save());
var defaultState = localStorageService.get($scope.defaultGridStateName);
if (!defaultState) {
localStorageService.set($scope.regularGridStateName, $scope.gridApi.saveState.save());
}
var gridState = localStorageService.get($scope.regularGridStateName);
if (gridState) {
gridApi.saveState.restore($scope, gridState);
}
}, 10);
This problem has been solved, just need to update to new version.
I had similar issue and this is due to the caching of column order. Try the following
gridApi.saveState.restore(this.scope, this.scope.tableState);
var columnDefsColMov = gridApi.grid.moveColumns.orderCache;
columnDefsColMov.length = 0;
columnDefsColMov.push.apply(columnDefsColMov, gridApi.grid.columns.slice());
gridApi.core.notifyDataChange(this.uiGridConstants.dataChange.COLUMN);

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

How to load a nested model into a Extjs form using loadRecord

I've created a script to dynamically generate a form, but I'm having problem loading the data of the nested model. I've tried loading the whole record and I've tried loading each sub store, but neither works.
I've through about using form.load(), but from my understanding that requires a proxy connection and also require to store json data inside a 'data' array.
Does anyone have any suggestions on how might I approach this problem?
<div id="view-#pageSpecificVar" class="grid-container even"></div>
<div id="button"></div>
<script>
Ext.define('HeaderForm', {
extend: 'Ext.form.Panel',
initComponent: function () {
var me = this;
Ext.applyIf(me, {
id: Ext.id(),
defaultType: 'textfield'
});
me.callParent(arguments);
}
});
// Define our data model
Ext.define('HeaderModel', {
extend: 'Ext.data.Model',
fields: [
{ name: 'HeaderSequence', type: 'int'}
],
hasMany:[
{ name: 'Columns', model: 'ColumnModel' }
],
proxy: {
type: 'ajax',
actionMethods: { create: 'POST', read: 'GET', update: 'POST', destroy: 'POST' },
url: '#Url.Content("~/Test/Header")',
timeout: 1200000,
},
});
Ext.define('ColumnModel', {
extend: 'Ext.data.Model',
fields: [
{ name: 'ColumnWidth', type: 'float'}
],
hasMany:[
{ name: 'Fields', model: 'FieldModel'}
],
belongsTo: 'HeaderModel'
});
Ext.define('FieldModel', {
extend: 'Ext.data.Model',
fields: [
{ name: 'XType', type: 'string'},
{ name: 'FieldLabel', type: 'string'},
{ name: 'Name', type: 'string'},
{ name: 'Data', type: 'string'},
{ name: 'FieldSpecify', type: 'bool'}
],
belongsTo: 'ColumnModel'
});
var store = Ext.create('Ext.data.Store', {
storeId: 'HeaderStore',
model: 'HeaderModel',
autoDestroy: true,
listeners: {
load: function (result, records, successful, eOpts) {
//console.log(result);
var form = dynamicForm(records[0]);
form.add(submitButton);
form.render('view-#pageSpecificVar');
}
}
});
store.load();
var dynamicForm = function(record) {
var form = new HeaderForm();
var columnContainer = new Ext.widget({
xtype: 'container',
layout: 'column'
});
var formItems = new Ext.util.MixedCollection();
Ext.each(record.ColumnsStore.data.items, function(item) {
Ext.iterate(item.data, function (key, value) {
var fieldContainer = new Ext.widget({
xtype: 'container',
columnWidth: value
});
Ext.each(item.FieldsStore.data.items, function(item) {
if(item.data["FieldSpecify"]) {
fieldContainer.add(new Ext.widget({
xtype: item.data["XType"],
fieldLabel: item.data["FieldLabel"],
name: item.data["Name"],
//value: item.data["Name"]
}));
}
}, this);
columnContainer.add(fieldContainer);
}, this);
}, this);
formItems.add(columnContainer);
form.add(formItems.items);
Ext.each(record.ColumnsStore.data.items, function(item) {
Ext.each(item.FieldsStore.data.items, function(fields) {
form.loadRecord(fields);
});
});
//form.loadRecord(record);
return form;
};
var submitButton = new Ext.widget({
xtype: 'toolbar',
dock: 'bottom',
items:[{
xtype: 'button',
text: 'Save',
handler: function(button) {
var basic = button.up('form').form;
basic.updateRecord(basic.getRecord());
var store = Ext.StoreMgr.get('HeaderStore');
store.each(function(record) {
record.dirty = true;
});
store.sync();
}
}]
});
</script>
Update
Sorry I probably didn't made it very clear. I'm having problem loading the store data into form fields. For static forms I normally use loadRecord to load the nested model into a form, but in this case all the fields are nested in their own little model, so would there be a way to load each nested model value into their own field with loadRecord?
The HeaderModel stores field set information.
The purpose of ColumnModel is to create the container that will surround a set of fields, for styling purpose. It simply creates two columns of fields.
The FieldModel stores the field specific attributes and data.
Here's an example of response json data...
{
"HeaderSequence":1,
"Columns":[{
"ColumnWidth":0.5,"Fields":[
{"XType":"textfield","FieldLabel":"FieldA","Name":"NameA","Data":"A","FieldSpecify":true},
{"XType":"textfield","FieldLabel":"FieldB","Name":"NameA","Data":"B","FieldSpecify":true}]
},{
"ColumnWidth":0.5,"Fields":[
{"XType":"textfield","FieldLabel":"FieldA2","Name":"NameA2","Data":"A2","FieldSpecify":true},
{"XType":"textfield","FieldLabel":"FieldB2","Name":"NameB2","Data":"B2","FieldSpecify":true}]
}
]
}
Thanks
I've figure out how to load the nested model into the form. We can't simply use load or loadRecord, as by default that method tries to get a model's data and iterate through the data object and call setValues.
What I have to do is manually get the basic form element and call setValues myself to assign the values.
// loop through each field store to load the data into the form by field id
Ext.each(record.ColumnsStore.data.items, function(item) {
Ext.each(item.FieldsStore.data.items, function(fields) {
form.getForm().setValues([{ id: fields.data['Id'], value: fields.data['DisplayName'] }]);
});
});
To Follow up with that, a custom submit handler needs to be put in place as well.
Which loops through the store and sets the submitted value to store before sync the store.
// define form submit button
var submitButton = new Ext.widget({
xtype: 'toolbar',
dock: 'bottom',
items:[{
xtype: 'button',
text: 'Save',
handler: function(button) {
// get basic form for button
var basic = button.up('form').form;
// get form submit values
var formSubmitValues = basic.getValues();
// get header store
var store = Ext.StoreMgr.get('HeaderStore');
// loop through each field store and update the data values by id from the form
store.each(function(record) {
Ext.each(record.ColumnsStore.data.items, function(item) {
Ext.each(item.FieldsStore.data.items, function(fields) {
fields.data['Data'] = formSubmitValues[fields.data['Id']];
});
});
// mark the record as dirty to be sync
record.dirty = true;
});
// sync store object with the database
store.sync();
}
}]
});
Have a look at this and this examples on how to load nested data into a nested model. You will also see how to access the associated data.
I'm not sure why you use record.ColumnsStore.data.items, as if record is of HeaderModel type, you should really get the columns store via record.Columns, and then iterate that store.
Would also help to see what JSON your server returns.

Categories

Resources