Search code examples
javascriptextjsextjs6extjs6-modernextjs6.2

Change textfield to textareafield


I need to change xtype from textfield to textareafield basing on a condition. I need to do something like this, but I cant update xtype

    Ext.define('app',{
    launch: function(){
        var i = 1;
        if (i == 1) {
           Ext.getCmp('myID').updateXtype('textareafield')
        }
    },
    items:[{
          xtype: 'fieldset',
          title: 'title'
        },
       items: [{
          xtype: 'textfield',
          label: 'label'
        }]]
        })

or i can use the viewmodel, but xtype is not bindable

Ext.define('app',{
        launch: function(){
            var i = 1;
            if (i == 1) {
              this.getViewModel().set('newXtype', 'textareafield');
           }
          },
          items:[{
                xtype: 'fieldset',
                title: 'title'
              },
             items: [{
                xtype: 'textfield',
                label: 'label',
                bind: {
                xtype: '{newXtype}'
                }
              }]]
              })

Solution

  • Exactly: you cannot bind xtype in this way. In the situation I would use a hidden binding . You will build the form with textfield and textareafield. Then switch the hidden binding depending on your use case (condition).

    https://fiddle.sencha.com/#view/editor&fiddle/2trf

    Ext.create('Ext.form.Panel', {
        title: 'Switch between textfield and textareafield',
        width: 360,
        bodyPadding: 10,
        renderTo: Ext.getBody(),
        viewModel: {
            data: {
                showTextfield: true
            }
        },
        defaults: {labelWidth: 120},
        tbar: [{
            text: 'Switch',
            handler: function(button) {
                let vm = this.up('panel').getViewModel();
                let showTextfield = vm.get('showTextfield');
    
                vm.set('showTextfield', !showTextfield)
            }
        }],
        items: [{
            xtype: 'textfield',
            fieldLabel: 'TEXTFIELD',
            bind: { hidden: '{showTextfield}'}
        },{
            xtype: 'textareafield',
            fieldLabel: 'TEXTAREAFIELD',
            bind: { hidden: '{!showTextfield}'}
        }]
    });