PDA

View Full Version : How to change form field type on fly?



lp1051
1 Apr 2014, 4:13 AM
Hi,

I've searched net but couldn't find any answer on this. The goal seems to be a quite simple: How to change form field (x)type in beforerender event handler, or actually any handler after the field is displayed?
I've made test fiddle here (https://fiddle.sencha.com/#fiddle/4m2), but attaching the same code here as well.
In the test example, I'm trying to change datefield into displayfield. But of course I'm interested in general concept of changing the field type from and into any available type. The form in my case is inside tabpanel, if it matters, that's why I use it in my test example.



Ext.application({
name : 'Fiddle',


launch : function() {
Ext.create('Ext.tab.Panel', {
bodyPadding: 5, // Don't want content to crunch against the borders
width: 300,
renderTo: Ext.getBody(),
items: [{
xtype: 'form',
title: 'Form',
items: [{
xtype: 'datefield',
fieldLabel: 'Start date',
value: new Date()
}, {
xtype: 'datefield',
fieldLabel: 'End date',
value: new Date()
}]
},{
title: 'Tab',
html: 'Some tab'
}],
buttons: [{
text: 'To display field',
handler: function() {
var panel = this.up('tabpanel');
Ext.each(panel.query('datefield'), function(field) {
field.xtype = 'displayfield';
});
panel.doLayout();
panel.doComponentLayout();
}
}],

listeners: {
beforerender: function() {
Ext.each(this.query('datefield'), function(field) {
field.xtype = 'displayfield';
});
this.doLayout();
this.doComponentLayout();
}
}
});
}
});


Any ideas how to achieve this? Thanks a lot for any help.

firefoxSafari
1 Apr 2014, 6:16 AM
The xtype is just a convenience that tells the framework what type to create. Once the component is created, its type cannot be changed. What you need to do is capture the initial config for the field you want to change, remove that field, and then add a new one based on that config.

4m8

lp1051
1 Apr 2014, 6:43 AM
Thanks a lot for your advice. I was hoping there was some hidden reconfigure method or similar that I missed. If I have to re-insert the element, it will create an additional problem - how to reinsert it into the same position if was on? Perhaps tab.insert(index, cfg) might fix it... I will try. Thanks again

lp1051
1 Apr 2014, 6:57 AM
Yes, using
tab.insert(tab.items.indexOf(field), cfg); works. Great!
Note: Of course tab.items.indexOf(field) must be called before tab.remove()...