PDA

View Full Version : Dynamically creating fields



mclovin
2 Jul 2009, 9:23 AM
Hello,

I am trying to add new objects (Label/TextField) to a panel when a button is clicked. I have looked through the forums and it appears that the following code should work:



var productName2 = new Ext.form.Label({
id: 'productName2',
text: 'iPod'
})
var price2 = new Ext.form.TextField({
id: 'price2',
value: '$299'
})

var myPanel = new Ext.Panel({
id: 'myPanel',
labelWidth: 75,
border:true,
width: 400,
layout:'table',
layoutConfig: {
columns: 2
},
items: [
this.productName = new Ext.form.Label({
text: 'PS3'
}),
this.price = new Ext.form.TextField({
value: '$399'
})
],
buttons: [{
type:'button',
text: 'Add Item',
handler:function(){
/* THIS DOES NOT WORK */
myPanel.add('productName2');
myPanel.add('price2');
myPanel.doLayout();
}
}]
});

/* THIS WORKS.... */
//myPanel.add('productName2');
//myPanel.add('price2');
//myPanel.doLayout();

myPanel.render('cart');


Per my inline comments, if I invoke the add function to the panel outside of the Ext.Panel definition it works on load. But if I keep it in the button handler function it will not work when the button is pressed.

Any thoughts??
Thanks,
-Jim

Animal
2 Jul 2009, 9:39 AM
You are adding strings. That won't work anywhere.

Animal
2 Jul 2009, 9:40 AM
OK, Strings are used as IDs. So it should work anywhere...

Animal
2 Jul 2009, 9:41 AM
The table layout is not dynamic in older versions of Ext 2.

mclovin
2 Jul 2009, 9:55 AM
The thing that baffles me is that it actually does work where I currently have the code commented out. The exact same syntax directly in the handler does not work. Could this be a scoping issue or something? Maybe I'm way off in my approach. Do you have an alternate suggestion as to how I could do this?

Animal
2 Jul 2009, 12:08 PM
It's because you add them before rendering.

Adding them after requires that the layout be dynamic, and table is not.

Use form layout, and a field with an associated fieldLabel config instead of a Label and a Field.

mclovin
2 Jul 2009, 1:03 PM
Ok, that does seems to work. However, I am trying to lay the form widgets out in a series of horizontal rows (which is why I went with table layout). I'm attaching a screenshot of what I'm ultimately going for. In short I am trying to create a form within a tab panel where I can dynamically add rows in the form horizontally upon a button click. Maybe the table layout isn't the best approach for this. Do you have any suggestions on how to achieve this?

Animal
2 Jul 2009, 1:07 PM
Use a subcontainer which is layout: 'table' for each row:



{
xtype: 'container',
autoEl: 'div',
layout: 'table',
layoutConfig: {
columns: 4
},
items: [ input1, input2, input3, input4 ]
}


And add new instances of that to a normal Container layout.

mclovin
2 Jul 2009, 1:12 PM
Thanks for all your help Animal! I will give this a whirl and let you know how it turns out

-Jim