Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autosizing textfield label in ExtJS

In ExtJS, is it possible to have the label of a textfield optimally sized to fit its text in one line?

The labelWidth property doesn't have an auto setting, and leaving it out completely has same effect as specifying the default value 100, which will cause a lengthy text to break over multiple lines:

http://jsfiddle.net/Qbw7r/

I would like to have the label just as wide as it takes to contain the whole text without wrapping, and the editable field fill up the rest of the available width.

like image 568
GOTO 0 Avatar asked Sep 13 '13 17:09

GOTO 0


1 Answers

You could also use Ext.util.TextMetrics to measure the length of your label and set the labelWidth accordingly. (See this fiddle).

var label = 'Changing text with variable length',
    tm = new Ext.util.TextMetrics(),
    n = tm.getWidth(label + ":"); //make sure we account for the field separator

Ext.create('Ext.form.Panel', {
    bodyPadding: 10,
    bodyStyle: 'background-color: #cef',
    items: [{
        xtype: 'textfield',
        emptyText: 'no data',
        fieldLabel: label,
        labelWidth: n
    }],
    margin: 25,
    renderTo: Ext.getBody()
});

If you need a more general solution, take a look at the example in the comment provided by slemmon in the ExtJS docs. Essentially, his example creates an extension of the text field which dynamically sets the label width based on the label. Here is his example:

Ext.define('MyTextfield', {
    extend: 'Ext.form.field.Text',
    xtype: 'mytextfield',
    initComponent: function () {
        var me = this,
            tm = new Ext.util.TextMetrics();

        me.labelWidth = tm.getWidth(me.fieldLabel) + 10;
        tm.destroy();

        me.callParent(arguments);
    }
});
like image 58
Towler Avatar answered Sep 24 '22 23:09

Towler