extjsextjs4extjs-mvc

Adding dynamic fields on click of button in extjs 4


I want to add a field dynamically when click on button in extjs 4.What I have done is added a onchange function on add button and write the adding textfield logic in that function. Here is my code.

Ext.define('AM.view.user.Edit', {
    extend: 'Ext.window.Window',
    alias : 'widget.useredit',
    requires: ['Ext.form.Panel'],
    title : 'Edit User',
    layout: 'fit',
    autoShow: true,
    height: 300,
    width: 280,
    id : 'mainPanel',
        initComponent: function() {
        this.items = [
            {
                xtype: 'form',
                id: 'dyForm',
                padding: '5 5 0 5',
                border: false,
                style: 'background-color: #fff;',

                items: [
                    {
                        xtype: 'textfield',
                        name : 'name',
                        fieldLabel: 'Name'
                    },
                    {
                        xtype: 'textfield',
                        name : 'email',
                        fieldLabel: 'Email'
                    }
                ]
            }
        ];

        this.buttons = [
            {
                text: 'Save',
                action: 'save'
            },
           {
                text: 'Add',
                scope: this,
                handler: this.onChange
            },
           ];

        this.callParent(arguments);
    },
    onChange : function(){alert('test');
         var form=Ext.getCmp("mainPanel");
        form.items.add(Ext.create("Ext.form.field.Text", {fieldLabel:"First Name"}));
        form.doLayout(true);
   }
});

And I also want that on edit of this form I will load data to those new fields that i have newly created dynamically.


Solution

  • Change the onChange function to

    onChange : function(btn){
        // var form=Ext.getCmp("mainPanel");
        var form = btn.up('window').down('form'); // this is a better approach
        form.add(Ext.create("Ext.form.field.Text", {fieldLabel:"First Name"}));
    }
    

    should do it. You added the field directly to the collection where you should have use the supplied add method of the form component.

    see JSFiddle