And-y
And-y

Reputation: 1524

TextArea which adapts Line with Linebreak after x characters

In our ExtJs5.1.2 project we want to have a textarea which breaks the line with a linefeed after x characters entered.

e.g. line should max be 5 characters long when entering 12345 the stay on one line and when entering 6 a new line with 6 is in the textarea.

12345
6

So when the user continuously enters text, the text is autoamtically adapted to a line length of 5.

12345
67890
12345
6...

I tried it with the following extend of the textarea, but it does not work as expected. The function adaptLines formats the value accordingly to a line length of 5, but it is not populated to the textarea itself.

Ext.define('LineAdaptTextField', {
    extend: 'Ext.form.field.TextArea',

    _removeNewLineRegEx: /\n/g,
    _lineAdaptRegEx: /(.{1,5})/g,

    // called when text is entered, but no effect of value in the textfield
    processRawValue: function(value) {
        value = this.callParent([value]);
        var processed = this.adaptLines(value);

        console.info('processRawValue("%s") to "%s"', value, processed);

        return processed;
    },

    // never be called when entering text
    transformRawValue: function(value) {
        value = this.callParent([value]);
        var transformed = this.adaptLines(value);

        console.info('transformRawValue("%s") to "%s"', value, transformed);

        return transformed;
    },

    // is called but no effect on the textfield
    valueToRaw: function (value) {
        value = this.callParent([value]);
        var rawValue = this.adaptLines(value);

        console.info('valueToRaw("%s") to "%s"', value, rawValue);

        return rawValue;
    },

    // never be called when entering text
    rawToValue: function (rawValue) {
        rawValue = this.callParent([rawValue]);
        var value = this.adaptLines(rawValue);

        console.info('valueToRaw("%s") to "%s"', rawValue, value);

        return value;
    },

    // add linefeed after 5 characters
    adaptLines: function(value){
        var noNewLines = value.replace(this._removeNewLineRegEx, '');
        return noNewLines.replace(this._lineAdaptRegEx, '$1\n').replace(/\n$/, '');
    }
});

For trying out the problem see this Fiddle.

Upvotes: 1

Views: 119

Answers (1)

Abdul Rehman Yawar Khan
Abdul Rehman Yawar Khan

Reputation: 1087

One of the solution to this issue will be to explicitly setting the formatted value. For example(fiddle), one can make use of change event:

listeners:{
    change: function ( field, newValue, oldValue, eOpts ){
        field.setValue(newValue);
    }
}

The value which is returned by rawToValue method, is available in newValue parameter of change event. Calling the setValue method by passing the newValueas argument will update the texteditor view.

Upvotes: 1

Related Questions