Ext js combo not working properly - javascript

I'm new in ExtJS and I'm trying to display a window with a combo, a cancel and an OK button but the combo does not seem to be working properly: It's not showing the label and when I click the picker (or the trigger) it does not show the list.
I need the combo to either accept free text and selected values but I don't know what I'm doing wrong. I went over Sencha api and forums but I can't work this out.
I hope you guys have a solution for this. Thanks and sorry if my English is not good enough.
function new_filter()
{
var ds_filter2 = new Ext.data.JsonStore({
url: 'forms-combobox-data-filters.php?user='+user_id,
fields: ['id', 'name'],
autoLoad: true/*,
totalProperty: "results"*/
});
var dlg = new Ext.Window(
{
title: 'Save Current Settings as a Filter',
id: 'frmFilter',
width: 350,
y: 200,
height: 120,
minWidth: 350,
minHeight: 100,
iconCls: 'save',
bodyStyle:'padding:0px 0px 0px 0px; background-color:#F5F5F5;',
modal: true,
resizable: false,
maximizable: false,
draggable:false,
closable: true,
closeAction: 'close',
hideMode: "offsets",
constrainHeader: true,
//autoLoad: { url : 'filter_form2.php', scripts: true},
keys: [
{ key: [Ext.EventObject.ENTER], handler: function() {
create_new_filter();
}
},
{ key: [Ext.EventObject.ESCAPE], handler: function() {
dlg.close();
}
}],
buttons:[
{
text : 'OK',
handler: function()
{
var selectedValue = Ext.getCmp('combo-new-filter').value; //selectedValue => Nombre
var rec = ds_filter2.getById(selectedValue); //rec => ID
//alert('rec: '+rec+'\nselected value: '+selectedValue);
if (rec == undefined ) //si el valor seleccionado no se encuentra en combo
{
create_new_filter(selectedValue);
dlg.close();
}
else
{
//alertar con el message box si se desea sobre escrbir el filtro
//ok---> grabar
//cancel--->cancelar
var selected_text = rec.get('name');
var id = rec.get('id');
//alert("selected text: "+selected_text);
Ext.MessageBox.confirm('Confirm','Are you sure you want to overwrite this filter "'+selected_text+'"?', function(btn)
{
if (btn=='yes')
{
var url = 'deleteFilter.php?filter='+id;
var mnmxmlhttp = Array ();
mnmxmlhttp = new myXMLHttpRequest ();
if (mnmxmlhttp)
{
mnmxmlhttp.open ("POST", url, true);
mnmxmlhttp.setRequestHeader ('Content-Type', 'application/x-www-form-urlencoded');
mnmxmlhttp.send ("");
mnmxmlhttp.onreadystatechange = function ()
{
if (mnmxmlhttp.readyState == 4)
{
create_new_filter(selected_text);
}
}
}
}
});
}
}
},
{
text : 'Cancel',
handler: function() {
dlg.close();
}
}
],
items:[
/*{
xtype: 'label',
forId: 'myFieldId',
text: 'Name of saved filter:',
},*/
{
id:'combo-new-filter',
labelAlign: 'left',
fieldLabel: 'Filter Name:',
xtype: 'combo',
store: ds_filter2,
//queryMode: 'local',
displayField:'name',
valueField: 'id',
//editable: true,
x: 110,
y: 20,
listeners: {
/*beforerender: function(combo){
combo.setValue("Select saved filter to apply");
},
select:{fn:function(combo, value) {
if (combo.getValue()>0){onSelectFilter(combo.getValue());}
}
}*/
}
}
]
});
dlg.show();
}

Your window needs to have the layout: 'form' configuration. In order to display fields, combos, etc, the layout that contains them needs to be a form one.

Related

javascript EXTJS close & reset

The previous programmer used EXTJS, with which I don't have a whole lot of familiarity with.
The application I am trying to fix has a modal called ADD ACCOUNT, with which a user can either manually type the various input fields or drag and drop an account already open into the modal.
The user can hit a reset button and clear the fields. However, if they don't clear the fields and they just close the window, when the window is reopened, the previous data is still there.
Basically, if the user decides to close the window, it needs to also reset and clear all the fields.
As stated, I am not too familiar with EXTJS. With that said, I will include the code below, which may be a lot. I will try not to include unnecessary code.
There are 2 files: accountGrid.php and accountGrid.js
I have isolated where I think the issue begins in accountGrid.js. Here is what I've found:
function addAccount(){
var AddAccountForm;
var fields = [
{name: 'must_have', mapping: 'must_have'},
{name: "*** there are like 50 of these, so I'll skip the rest ***"}
];
AddAccount = new Ext.FormPanel({
autoScroll: true,
monitorValid: true,
defaultType: 'textfield',
items:
[
{
xtype: 'fieldset',
title: 'Required Information',
collapsible: true,
autoHeight: true,
defaultType: 'textfield',
items: [*** random fields here ***]
},
{
xtype: 'fieldset',
title: 'Optional Information',
collapsible: true,
collapsed: true,
autoHeight: true,
defaultType: 'textfield',
items: [*** random fields here ***]
}
],
buttons: *** this is where the buttons being ***
[
{
text: 'Submit',
id: 'submitAdd',
formBind: true,
handler: function(){
AddAccountForm.getForm().submit({
url: 'data-entry.php', *** hope I don't need to show this file's code ***
waitMsg: 'Updating Record...',
success: function(form, action){
obj = Ext.util.JSON.decode(action.response.responseText);
AddAccountForm.getForm().reset(); *** notice this reset function ***
delete BookingDataStore.lastParams;
BookingDataStore.removeAll();
var sa = Ext.getCmp('salesArea').getValue();
*** there are few more of these var sa fiels ***
BookingDataStore.on('beforewrite', function(store, options){
Ext.apply(options.params, {
task: 'LISTING',
salesarea: sa,
*** there are a few more of these variables ***
*** honestly, I'm not sure what these are ***
});
});
BookingDataStore.reload();
Ext.Msg.alert('Success', 'The record has been saved.');
AddAccountWindow.close();
},
failure: function(form, action){
if(action.failureType == 'server'){
obj = Ext.util.JSON.decode(action.response.responseText);
Ext.Msg.alert('Error','Your account was not submitted.'+obj['error']);
}
else{
Ext.Msg.alert('Warning','There server is unreachable: ' +action.response.responseText);
}
}
});
}
},
{
text: 'Reset', *** here is the reset ***
handler: function() {AddAccountForm.getForm().reset();}
},
{ *** 2ND EDIT ***
text: 'Close',
AddAccountForm.getForm().submit({
handler: function() {
Ext.Msg.alert('close');
};
});
} *** 2ND EDIT CONTINUED BELOW ***
],
keys: [{
key: [10,13], fn: function(){
var b = Ext.getCmp('submitAdd');
b.focus();
b.fireEvent("click", b);
}
}]
});
AddAccountWindow = new Ext.Window({
title: 'Add Account',
closable: true,
closeAction: 'close',
y: 5,
plain: true,
layout: 'fit',
stateful: false,
items: AddAccountForm
});
AddAccountWindow.show(this);
}
That was what I think is the major portion of the accountGrid.js. There was some more code for the drag and drop feature, but that was not necessary for me to display.
I did not think this code was this long. I haven't even gotten to the php file code. SMH.
Here is the code from accountGrid.php:
var AddAccountForm = new Ext.FormPanel({
id: 'AddAccountForm',
autoScroll: true,
monitorValid: true,
submitEmptyText: false,
defaultType: 'textfield',
items:
[
{
xtype: 'fieldset',
id: 'reqFieldSet',
title: 'Required Information',
*** there are more parameters, I'll skip to the buttons ***
}
],
buttons:
[
{
text: 'Submit',
id: 'submitAdd',
formBind: true,
handler: function(){
var pc = partnerCodeField.getValue();
var pn = partnerNameField.getValue();
AddAccountForm.getForm().submit({
url: 'data-entry.php',
waitMsg: 'Updating Record....',
params: {partner_code:pc, partner_name:pn},
success: function(form, action){
obj = Ext.util.JSON.decode(action.response.responseText);
AddAccountForm.getForm()reset();
delete BookingDataStore.lastParams;
BookingDataStore.removeAll();
BookingDataStore.on('beforeload', function(store, option){
Ext.apply(options.params, {
ns_task: "SEARCHING"
});
});
BookingDataStore.load();
TradeTotalsDataStore.reload();
Ext.Msg.alert('Success','The record has been saved.');
AddAccountWindow.hide();
},
failure: function(form, action){
if(action.failureType == 'server'){
obj = Ext.util.JSON.decode(action.response.responseText);
Ext.Msg.alert('Error','Your account was not submitted.'+obj['error']);
}
else{
Ext.Msg.alert('Warning','The server is unreachable:'+action.response.responseText);
}
}
});
}
},
{
text: 'Reset',
handler: function(){
AddAccountForm.getForm().reset();
partnerCodeField.enable();
partnerNameField.enable();
}
}, *** 2ND EDIT ***
{
text: 'Close',
handler: function(){
AddAccountForm.getForm().reset();
AddAccountWindow.close();
partnerCodeField.enable();
partnerNameField.enable();
}
} *** END 2ND EDIT ***
],
keys:
[
{
key: [10, 13], fn: function(){
var b = Ext.getCmp('submitAdd');
b.focus();
b.fireEvent("click", b);
}
}
]
});
var AddAccountWindow = new Ext.Window({
title: 'Add Account',
closeable: true,
closeAction: 'hide',
y: 5,
plain: true,
layout: 'fit',
stateful: false,
items: AddAccountForm
});
I just saw this immediately after the code directly above:
function addAccount(){
AddAccountWindow.show(this);
*** beneath this is code for the drag & drop features ***
*** I don't think I need to show that ***
}
I'm not sure why the code from accountGrid.php and accountGrid.js look similar. I apologize for the amount of code. I just really need help breaking this code down.
Just to reiterate, when they click the X button at the top-right of the window, it needs to clear the modal form and then close.
You have a window with a child named accountform.
What you want to do is add a listener for the close button of the window and add code to clear your form.
You already have this:
new Ext.Window({
closable: true, //adds the close button
closeAction: 'close', //'close' isn't supported (use 'hide')
Add a listener to it:
{
//....
closable: true,
listeners: {
close:function(){
//put clear form code here
}
}
}
Add code to clear the form:
AddAccountForm.getForm().reset(true)
Finally it looks someting like this:
var AddAccountWindow = new Ext.Window({
title: 'Add Account',
closeable: true,
closeAction: 'hide',
y: 5,
plain: true,
layout: 'fit',
stateful: false,
items: AddAccountForm,
listeners: {
close:function(){
AddAccountForm.getForm().reset(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

show message box ext window beforeclose event

I want to show message box when user click (X) button of ext window, and on 'ok' button of message box window will close. I wrote the code but it closes window first than show message box. Here is the code:
var assignReportFlag = 0;
var assignReportLoader = function(title,url){
var panel = new Ext.FormPanel({
id: 'arptLoader',
height: 485,
border: false,
layout: 'fit',
autoScroll: true,
method:'GET',
waitMsg: 'Retrieving form data',
waitTitle: 'Loading...',
autoLoad: {url: url,scripts: true}
});
var cqok = new Ext.Button({
text:'OK',
id:'1',
handler: function(){
if(assignReportFlag == 1){
assignReportFlag = 0;
Ext.MessageBox.alert('Status', 'Changes has been saved successfully',showResult);
}else{
assignReportWindow.close();
}
}
});
var assignReportWindow = new Ext.Window({
layout:'fit',
title: title,
height:Ext.getBody().getViewSize().height - 60,
width:Ext.getBody().getViewSize().width-20,
closable: true,
modal:true,
resizable: false,
autoScroll:true,
plain: true,
border: false,
items: [panel],
buttons: [cqok],
listeners:{
beforeclose:function(){
if(assignReportFlag == 1){
assignReportFlag = 0;
Ext.MessageBox.alert('Status', 'Changes has been saved successfully',showResult);
}else{
assignReportWindow.destroy();
}
}
}
});
function showResult(btn){
assignReportWindow.destroy();
};
assignReportWindow.show();
};
Thanks
In your beforeclose listener return false to stop the close event being fired.
This works fine for me.Have a look
http://jsfiddle.net/DrjTS/266/
var cqok = new Ext.Button({
text:'OK',
id:'1',
handler: function(){
Ext.MessageBox.alert('Status', 'Changes has been saved successfully',showResult);
}
});
Ext.create('Ext.panel.Panel', {
title: 'Hello',
width: 200,
renderTo: Ext.getBody(),
items:[
{
xtype:'button',
text:'SUBMIT',
handler:function(thisobj)
{
Ext.create('Ext.window.Window', {
id:'W',
height: 200,
width: 400,
layout: 'fit',
buttons: [cqok],
listeners:{
beforeclose:function(){
Ext.MessageBox.alert('Status', 'Changes has been saved');
}
}
}).show();
}
}
]
});
function showResult(btn){
Ext.getCmp('W').destroy();
};

jqGrid SetCell and SaveCell blanking out the cell after closing a modal dialog

I have a cell-editable jqgrid with a column that has an edittype of 'button'. When the cell is clicked, the button appears. when the button is clicked, a modal dialog appears allowing the user to select a value from a grid. This is all working fine.
When the user clicks the 'OK' button on the modal dialog after picking a value from the grid, I'd like to set the cell value with the value selected by the user and save the cell.
Instead of setting and saving the cell value, the cell is blanked out. Not sure why.
Here is the relevant jqGrid / modal dialog code:
// global variables
base.selectedCode = null;
base.liaGridSelectedId = null;
base.liaGridSelectedICol = null;
base.liaGridSelectedIRow = null;
$("#liaGrid").jqGrid({
datatype: "local",
data: base.liaGridData,
cellEdit: true,
cellsubmit: 'clientArray',
height: 140,
colNames: ['ID', 'Class Code', 'State', 'Location Type'],
colModel: [
{ name: 'id', index: 'id', width: 90, sorttype: "int", editable: false, hidden: true },
{ name: 'ClassCode', index: 'ClassCode', width: 90, sortable: false, editable: true, edittype: "button",
editoptions: {
dataEvents: [{
type: 'click',
fn: function (e) {
e.preventDefault();
var rowid = $('#liaGrid').jqGrid('getGridParam', 'selrow');
base.liaGridSelectedId = parseInt(rowid);
$('#class-dialog').dialog('option', { width: 100, height: 200, position: 'center', title: 'Pick a Class' });
$('#class-dialog').dialog('open');
return true;
}
}]
}
},
{ name: 'LocationType', index: 'LocationType', width: 90, sortable: false, editable: true, edittype: "select", editoptions: { value: "0:;1:Rural;2:Suburban;3:Urban"} }
],
caption: "Liability Model",
beforeEditCell: function (rowid, cellname, value, iRow, iCol) {
base.liaGridSelectedICol = iCol;
base.liaGridSelectedIRow = iRow;
}
});
var infoDialog = $('#class-dialog').dialog({
autoOpen: false,
modal: true,
show: 'fade',
hide: 'fade',
resizable: true,
buttons: {
"Ok": function () {
if (base.selectedCode != null) {
$("#liaGrid").jqGrid('setCell', base.liaGridSelectedId, 'ClassCode', base.selectedCode);
$("#liaGrid").jqGrid('saveCell', base.liaGridSelectedIRow, base.liaGridSelectedICol);
$(this).dialog("close");
}
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
As seen above, I'm attempting to use jqGrid('setCell') and jqGrid('saveCell') to update and save the contents of the cell. Not sure why this fails to succeed.
I got this to work in case anyone encounters a similar issue. I had to add the afterSaveCell handler to the grid:
afterSaveCell: function (rowid, name, val, iRow, iCol) {
if (base.liaGridSelectedICol == 1) {
$("#liaGrid").jqGrid('setRowData', rowid, { ClassCode: base.selectedCode });
}
}
FYI - base.selectedCode is set in the modal.
Odd thing, this only worked after calling the setCell and saveCell methods. Without these unsuccessful calls to set and save at the cell level, the above handler was not called.
If someone has a more appropriate approach to solving this problem I'd like to hear it.
Thanks

Get Grid Cell Value on Hover in ExtJS4

I have the following code in a grid:
var grid = Ext.create('Ext.grid.Panel', {
store: store,
stateful: true,
stateId: 'stateGrid',
columns: [
{
text : 'Job ID',
width : 75,
sortable : true,
dataIndex: 'id'
},
{
text : 'File Name',
width : 75,
sortable : true,
dataIndex: 'filename',
listeners : {
'mouseover' : function(iView, iCellEl,
iColIdx, iRecord, iRowEl, iRowIdx, iEvent) {
var zRec = iView.getRecord(iRowEl);
alert(zRec.data.id);
}
}
...etc...
I can't figure out how to get the cell value of the first column in the row. I've also tried:
var record = grid.getStore().getAt(iRowIdx); // Get the Record
alert(iView.getRecord().get('id'));
Any ideas?
Thanks in advance!
It's easier than what you have.
Look at the Company column config here for an example-
http://jsfiddle.net/qr2BJ/4580/
Edit:
Part of grid definition code:
....
columns: [
{
text : 'Company',
flex : 1,
sortable : false,
dataIndex: 'company',
renderer : function (value, metaData, record, row, col, store, gridView) {
metaData.tdAttr = 'data-qtip="' + record.get('price') + ' is the price of ' + value + '"';
return value;
}
},
....
You can add a handler instead of a listener.
{
header: 'DETAILS',
xtype:'actioncolumn',
align:'center',
width: 70,
sortable: false,
items: [
{
icon: '/icons/details_icon.png', // Use a URL in the icon config
tooltip: 'Show Details',
handler: function(grid, rowIndex, colIndex) {
var record = grid.getStore().getAt(rowIndex);
}

Categories

Resources