3 This file is part of Ext JS 4
5 Copyright (c) 2011 Sencha Inc
7 Contact: http://www.sencha.com/contact
9 GNU General Public License Usage
10 This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file. Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
12 If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
16 * @docauthor Jason Johnston <jason@sencha.com>
18 * Base class for form fields that provides default event handling, rendering, and other common functionality
19 * needed by all form field types. Utilizes the {@link Ext.form.field.Field} mixin for value handling and validation,
20 * and the {@link Ext.form.Labelable} mixin to provide label and error message display.
22 * In most cases you will want to use a subclass, such as {@link Ext.form.field.Text} or {@link Ext.form.field.Checkbox},
23 * rather than creating instances of this class directly. However if you are implementing a custom form field,
24 * using this as the parent class is recommended.
26 * # Values and Conversions
28 * Because BaseField implements the Field mixin, it has a main value that can be initialized with the
29 * {@link #value} config and manipulated via the {@link #getValue} and {@link #setValue} methods. This main
30 * value can be one of many data types appropriate to the current field, for instance a {@link Ext.form.field.Date Date}
31 * field would use a JavaScript Date object as its value type. However, because the field is rendered as a HTML
32 * input, this value data type can not always be directly used in the rendered field.
34 * Therefore BaseField introduces the concept of a "raw value". This is the value of the rendered HTML input field,
35 * and is normally a String. The {@link #getRawValue} and {@link #setRawValue} methods can be used to directly
36 * work with the raw value, though it is recommended to use getValue and setValue in most cases.
38 * Conversion back and forth between the main value and the raw value is handled by the {@link #valueToRaw} and
39 * {@link #rawToValue} methods. If you are implementing a subclass that uses a non-String value data type, you
40 * should override these methods to handle the conversion.
44 * The content of the field body is defined by the {@link #fieldSubTpl} XTemplate, with its argument data
45 * created by the {@link #getSubTplData} method. Override this template and/or method to create custom
51 * // A simple subclass of BaseField that creates a HTML5 search field. Redirects to the
52 * // searchUrl when the Enter key is pressed.222
53 * Ext.define('Ext.form.SearchField', {
54 * extend: 'Ext.form.field.Base',
55 * alias: 'widget.searchfield',
57 * inputType: 'search',
59 * // Config defining the search URL
60 * searchUrl: 'http://www.google.com/search?q={0}',
62 * // Add specialkey listener
63 * initComponent: function() {
65 * this.on('specialkey', this.checkEnterKey, this);
68 * // Handle enter key presses, execute the search if the field has a value
69 * checkEnterKey: function(field, e) {
70 * var value = this.getValue();
71 * if (e.getKey() === e.ENTER && !Ext.isEmpty(value)) {
72 * location.href = Ext.String.format(this.searchUrl, value);
77 * Ext.create('Ext.form.Panel', {
78 * title: 'BaseField Example',
82 * // Fields will be arranged vertically, stretched to full width
88 * xtype: 'searchfield',
89 * fieldLabel: 'Search',
92 * renderTo: Ext.getBody()
95 Ext.define('Ext.form.field.Base', {
96 extend: 'Ext.Component',
98 labelable: 'Ext.form.Labelable',
99 field: 'Ext.form.field.Field'
101 alias: 'widget.field',
102 alternateClassName: ['Ext.form.Field', 'Ext.form.BaseField'],
103 requires: ['Ext.util.DelayedTask', 'Ext.XTemplate', 'Ext.layout.component.field.Field'],
106 * @cfg {Ext.XTemplate} fieldSubTpl
107 * The content of the field body is defined by this config option.
109 fieldSubTpl: [ // note: {id} here is really {inputId}, but {cmpId} is available
110 '<input id="{id}" type="{type}" ',
111 '<tpl if="name">name="{name}" </tpl>',
112 '<tpl if="size">size="{size}" </tpl>',
113 '<tpl if="tabIdx">tabIndex="{tabIdx}" </tpl>',
114 'class="{fieldCls} {typeCls}" autocomplete="off" />',
123 * The name of the field. This is used as the parameter name when including the field value
124 * in a {@link Ext.form.Basic#submit form submit()}. If no name is configured, it falls back to the {@link #inputId}.
125 * To prevent the field from being included in the form submit, set {@link #submitValue} to false.
129 * @cfg {String} inputType
130 * The type attribute for input fields -- e.g. radio, text, password, file. The extended types
131 * supported by HTML5 inputs (url, email, etc.) may also be used, though using them will cause older browsers to
132 * fall back to 'text'.
134 * The type 'password' must be used to render that field type currently -- there is no separate Ext component for
135 * that. You can use {@link Ext.form.field.File} which creates a custom-rendered file upload field, but if you want
136 * a plain unstyled file input you can use a BaseField with inputType:'file'.
141 * @cfg {Number} tabIndex
142 * The tabIndex for this field. Note this only applies to fields that are rendered, not those which are built via
147 * @cfg {String} invalidText
148 * The error text to use when marking a field invalid and no message is provided
150 invalidText : 'The value in this field is invalid',
153 * @cfg {String} [fieldCls='x-form-field']
154 * The default CSS class for the field input
156 fieldCls : Ext.baseCSSPrefix + 'form-field',
159 * @cfg {String} fieldStyle
160 * Optional CSS style(s) to be applied to the {@link #inputEl field input element}. Should be a valid argument to
161 * {@link Ext.Element#applyStyles}. Defaults to undefined. See also the {@link #setFieldStyle} method for changing
162 * the style after initialization.
166 * @cfg {String} [focusCls='x-form-focus']
167 * The CSS class to use when the field receives focus
169 focusCls : Ext.baseCSSPrefix + 'form-focus',
172 * @cfg {String} dirtyCls
173 * The CSS class to use when the field value {@link #isDirty is dirty}.
175 dirtyCls : Ext.baseCSSPrefix + 'form-dirty',
178 * @cfg {String[]} checkChangeEvents
179 * A list of event names that will be listened for on the field's {@link #inputEl input element}, which will cause
180 * the field's value to be checked for changes. If a change is detected, the {@link #change change event} will be
181 * fired, followed by validation if the {@link #validateOnChange} option is enabled.
183 * Defaults to ['change', 'propertychange'] in Internet Explorer, and ['change', 'input', 'textInput', 'keyup',
184 * 'dragdrop'] in other browsers. This catches all the ways that field values can be changed in most supported
185 * browsers; the only known exceptions at the time of writing are:
187 * - Safari 3.2 and older: cut/paste in textareas via the context menu, and dragging text into textareas
188 * - Opera 10 and 11: dragging text into text fields and textareas, and cut via the context menu in text fields
190 * - Opera 9: Same as Opera 10 and 11, plus paste from context menu in text fields and textareas
192 * If you need to guarantee on-the-fly change notifications including these edge cases, you can call the
193 * {@link #checkChange} method on a repeating interval, e.g. using {@link Ext.TaskManager}, or if the field is within
194 * a {@link Ext.form.Panel}, you can use the FormPanel's {@link Ext.form.Panel#pollForChanges} configuration to set up
195 * such a task automatically.
197 checkChangeEvents: Ext.isIE && (!document.documentMode || document.documentMode < 9) ?
198 ['change', 'propertychange'] :
199 ['change', 'input', 'textInput', 'keyup', 'dragdrop'],
202 * @cfg {Number} checkChangeBuffer
203 * Defines a timeout in milliseconds for buffering {@link #checkChangeEvents} that fire in rapid succession.
204 * Defaults to 50 milliseconds.
206 checkChangeBuffer: 50,
208 componentLayout: 'field',
211 * @cfg {Boolean} readOnly
212 * true to mark the field as readOnly in HTML.
214 * **Note**: this only sets the element's readOnly DOM attribute. Setting `readOnly=true`, for example, will not
215 * disable triggering a ComboBox or Date; it gives you the option of forcing the user to choose via the trigger
216 * without typing in the text box. To hide the trigger use `{@link Ext.form.field.Trigger#hideTrigger hideTrigger}`.
221 * @cfg {String} readOnlyCls
222 * The CSS class applied to the component's main element when it is {@link #readOnly}.
224 readOnlyCls: Ext.baseCSSPrefix + 'form-readonly',
227 * @cfg {String} inputId
228 * The id that will be given to the generated input DOM element. Defaults to an automatically generated id. If you
229 * configure this manually, you must make sure it is unique in the document.
233 * @cfg {Boolean} validateOnBlur
234 * Whether the field should validate when it loses focus. This will cause fields to be validated
235 * as the user steps through the fields in the form regardless of whether they are making changes to those fields
236 * along the way. See also {@link #validateOnChange}.
238 validateOnBlur: true,
243 baseCls: Ext.baseCSSPrefix + 'field',
245 maskOnDisable: false,
248 initComponent : function() {
253 me.subTplData = me.subTplData || {};
258 * Fires when this field receives input focus.
259 * @param {Ext.form.field.Base} this
264 * Fires when this field loses input focus.
265 * @param {Ext.form.field.Base} this
270 * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. To handle other keys
271 * see {@link Ext.util.KeyMap}. You can check {@link Ext.EventObject#getKey} to determine which key was
272 * pressed. For example:
274 * var form = new Ext.form.Panel({
277 * fieldLabel: 'Field 1',
281 * fieldLabel: 'Field 2',
284 * specialkey: function(field, e){
285 * // e.HOME, e.END, e.PAGE_UP, e.PAGE_DOWN,
286 * // e.TAB, e.ESC, arrow keys: e.LEFT, e.RIGHT, e.UP, e.DOWN
287 * if (e.{@link Ext.EventObject#getKey getKey()} == e.ENTER) {
288 * var form = field.up('form').getForm();
298 * @param {Ext.form.field.Base} this
299 * @param {Ext.EventObject} e The event object
308 // Default name to inputId
310 me.name = me.getInputId();
315 * Returns the input id for this field. If none was specified via the {@link #inputId} config, then an id will be
316 * automatically generated.
318 getInputId: function() {
319 return this.inputId || (this.inputId = Ext.id());
323 * Creates and returns the data object to be used when rendering the {@link #fieldSubTpl}.
324 * @return {Object} The template data
327 getSubTplData: function() {
330 inputId = me.getInputId();
332 return Ext.applyIf(me.subTplData, {
335 name: me.name || inputId,
339 fieldCls: me.fieldCls,
341 typeCls: Ext.baseCSSPrefix + 'form-' + (type === 'password' ? 'text' : type)
345 afterRender: function() {
349 this.inputEl.selectable();
354 * Gets the markup to be inserted into the outer template's bodyEl. For fields this is the actual input element.
356 getSubTplMarkup: function() {
357 return this.getTpl('fieldSubTpl').apply(this.getSubTplData());
360 initRenderTpl: function() {
362 if (!me.hasOwnProperty('renderTpl')) {
363 me.renderTpl = me.getTpl('labelableRenderTpl');
365 return me.callParent();
368 initRenderData: function() {
369 return Ext.applyIf(this.callParent(), this.getLabelableRenderData());
373 * Set the {@link #fieldStyle CSS style} of the {@link #inputEl field input element}.
374 * @param {String/Object/Function} style The style(s) to apply. Should be a valid argument to {@link
375 * Ext.Element#applyStyles}.
377 setFieldStyle: function(style) {
379 inputEl = me.inputEl;
381 inputEl.applyStyles(style);
383 me.fieldStyle = style;
387 onRender : function() {
389 fieldStyle = me.fieldStyle;
391 me.onLabelableRender();
394 * @property {Ext.Element} inputEl
395 * The input Element for this Field. Only available after the field has been rendered.
397 me.addChildEls({ name: 'inputEl', id: me.getInputId() });
399 me.callParent(arguments);
401 // Make the stored rawValue get set as the input element's value
402 me.setRawValue(me.rawValue);
405 me.setReadOnly(true);
411 me.setFieldStyle(fieldStyle);
414 me.renderActiveError();
417 initAria: function() {
421 // Associate the field to the error message element
422 me.getActionEl().dom.setAttribute('aria-describedby', Ext.id(me.errorEl));
425 getFocusEl: function() {
429 isFileUpload: function() {
430 return this.inputType === 'file';
433 extractFileInput: function() {
435 fileInput = me.isFileUpload() ? me.inputEl.dom : null,
438 clone = fileInput.cloneNode(true);
439 fileInput.parentNode.replaceChild(clone, fileInput);
440 me.inputEl = Ext.get(clone);
445 // private override to use getSubmitValue() as a convenience
446 getSubmitData: function() {
450 if (!me.disabled && me.submitValue && !me.isFileUpload()) {
451 val = me.getSubmitValue();
454 data[me.getName()] = val;
461 * Returns the value that would be included in a standard form submit for this field. This will be combined with the
462 * field's name to form a name=value pair in the {@link #getSubmitData submitted parameters}. If an empty string is
463 * returned then just the name= will be submitted; if null is returned then nothing will be submitted.
465 * Note that the value returned will have been {@link #processRawValue processed} but may or may not have been
466 * successfully {@link #validate validated}.
468 * @return {String} The value to be submitted, or null.
470 getSubmitValue: function() {
471 return this.processRawValue(this.getRawValue());
475 * Returns the raw value of the field, without performing any normalization, conversion, or validation. To get a
476 * normalized and converted value see {@link #getValue}.
477 * @return {String} value The raw String value of the field
479 getRawValue: function() {
481 v = (me.inputEl ? me.inputEl.getValue() : Ext.value(me.rawValue, ''));
487 * Sets the field's raw value directly, bypassing {@link #valueToRaw value conversion}, change detection, and
488 * validation. To set the value with these additional inspections see {@link #setValue}.
489 * @param {Object} value The value to set
490 * @return {Object} value The field value that is set
492 setRawValue: function(value) {
494 value = Ext.value(value, '');
497 // Some Field subclasses may not render an inputEl
499 me.inputEl.dom.value = value;
505 * Converts a mixed-type value to a raw representation suitable for displaying in the field. This allows controlling
506 * how value objects passed to {@link #setValue} are shown to the user, including localization. For instance, for a
507 * {@link Ext.form.field.Date}, this would control how a Date object passed to {@link #setValue} would be converted
508 * to a String for display in the field.
510 * See {@link #rawToValue} for the opposite conversion.
512 * The base implementation simply does a standard toString conversion, and converts {@link Ext#isEmpty empty values}
513 * to an empty string.
515 * @param {Object} value The mixed-type value to convert to the raw representation.
516 * @return {Object} The converted raw value.
518 valueToRaw: function(value) {
519 return '' + Ext.value(value, '');
523 * Converts a raw input field value into a mixed-type value that is suitable for this particular field type. This
524 * allows controlling the normalization and conversion of user-entered values into field-type-appropriate values,
525 * e.g. a Date object for {@link Ext.form.field.Date}, and is invoked by {@link #getValue}.
527 * It is up to individual implementations to decide how to handle raw values that cannot be successfully converted
528 * to the desired object type.
530 * See {@link #valueToRaw} for the opposite conversion.
532 * The base implementation does no conversion, returning the raw value untouched.
534 * @param {Object} rawValue
535 * @return {Object} The converted value.
537 rawToValue: function(rawValue) {
542 * Performs any necessary manipulation of a raw field value to prepare it for {@link #rawToValue conversion} and/or
543 * {@link #validate validation}, for instance stripping out ignored characters. In the base implementation it does
544 * nothing; individual subclasses may override this as needed.
546 * @param {Object} value The unprocessed string value
547 * @return {Object} The processed string value
549 processRawValue: function(value) {
554 * Returns the current data value of the field. The type of value returned is particular to the type of the
555 * particular field (e.g. a Date object for {@link Ext.form.field.Date}), as the result of calling {@link #rawToValue} on
556 * the field's {@link #processRawValue processed} String value. To return the raw String value, see {@link #getRawValue}.
557 * @return {Object} value The field value
559 getValue: function() {
561 val = me.rawToValue(me.processRawValue(me.getRawValue()));
567 * Sets a data value into the field and runs the change detection and validation. To set the value directly
568 * without these inspections see {@link #setRawValue}.
569 * @param {Object} value The value to set
570 * @return {Ext.form.field.Field} this
572 setValue: function(value) {
574 me.setRawValue(me.valueToRaw(value));
575 return me.mixins.field.setValue.call(me, value);
580 onDisable: function() {
582 inputEl = me.inputEl;
585 inputEl.dom.disabled = true;
590 onEnable: function() {
592 inputEl = me.inputEl;
595 inputEl.dom.disabled = false;
600 * Sets the read only state of this field.
601 * @param {Boolean} readOnly Whether the field should be read only.
603 setReadOnly: function(readOnly) {
605 inputEl = me.inputEl;
607 inputEl.dom.readOnly = readOnly;
608 inputEl.dom.setAttribute('aria-readonly', readOnly);
610 me[readOnly ? 'addCls' : 'removeCls'](me.readOnlyCls);
611 me.readOnly = readOnly;
615 fireKey: function(e){
616 if(e.isSpecialKey()){
617 this.fireEvent('specialkey', this, Ext.create('Ext.EventObjectImpl', e));
622 initEvents : function(){
624 inputEl = me.inputEl,
628 me.mon(inputEl, Ext.EventManager.getKeyEvent(), me.fireKey, me);
629 me.mon(inputEl, 'focus', me.onFocus, me);
631 // standardise buffer across all browsers + OS-es for consistent event order.
632 // (the 10ms buffer for Editors fixes a weird FF/Win editor issue when changing OS window focus)
633 me.mon(inputEl, 'blur', me.onBlur, me, me.inEditor ? {buffer:10} : null);
635 // listen for immediate value changes
636 onChangeTask = Ext.create('Ext.util.DelayedTask', me.checkChange, me);
637 me.onChangeEvent = onChangeEvent = function() {
638 onChangeTask.delay(me.checkChangeBuffer);
640 Ext.each(me.checkChangeEvents, function(eventName) {
641 if (eventName === 'propertychange') {
642 me.usesPropertychange = true;
644 me.mon(inputEl, eventName, onChangeEvent);
650 doComponentLayout: function() {
652 inputEl = me.inputEl,
653 usesPropertychange = me.usesPropertychange,
654 ename = 'propertychange',
655 onChangeEvent = me.onChangeEvent;
657 // In IE if propertychange is one of the checkChangeEvents, we need to remove
658 // the listener prior to layout and re-add it after, to prevent it from firing
659 // needlessly for attribute and style changes applied to the inputEl.
660 if (usesPropertychange) {
661 me.mun(inputEl, ename, onChangeEvent);
663 me.callParent(arguments);
664 if (usesPropertychange) {
665 me.mon(inputEl, ename, onChangeEvent);
670 preFocus: Ext.emptyFn,
673 onFocus: function() {
675 focusCls = me.focusCls,
676 inputEl = me.inputEl;
678 if (focusCls && inputEl) {
679 inputEl.addCls(focusCls);
683 me.componentLayout.onFocus();
684 me.fireEvent('focus', me);
689 beforeBlur : Ext.emptyFn,
694 focusCls = me.focusCls,
695 inputEl = me.inputEl;
702 if (focusCls && inputEl) {
703 inputEl.removeCls(focusCls);
705 if (me.validateOnBlur) {
709 me.fireEvent('blur', me);
714 postBlur : Ext.emptyFn,
718 * @private Called when the field's dirty state changes. Adds/removes the {@link #dirtyCls} on the main element.
719 * @param {Boolean} isDirty
721 onDirtyChange: function(isDirty) {
722 this[isDirty ? 'addCls' : 'removeCls'](this.dirtyCls);
727 * Returns whether or not the field value is currently valid by {@link #getErrors validating} the
728 * {@link #processRawValue processed raw value} of the field. **Note**: {@link #disabled} fields are
729 * always treated as valid.
731 * @return {Boolean} True if the value is valid, else false
733 isValid : function() {
735 return me.disabled || me.validateValue(me.processRawValue(me.getRawValue()));
740 * Uses {@link #getErrors} to build an array of validation errors. If any errors are found, they are passed to
741 * {@link #markInvalid} and false is returned, otherwise true is returned.
743 * Previously, subclasses were invited to provide an implementation of this to process validations - from 3.2
744 * onwards {@link #getErrors} should be overridden instead.
746 * @param {Object} value The value to validate
747 * @return {Boolean} True if all validations passed, false if one or more failed
749 validateValue: function(value) {
751 errors = me.getErrors(value),
752 isValid = Ext.isEmpty(errors);
753 if (!me.preventMark) {
757 me.markInvalid(errors);
765 * Display one or more error messages associated with this field, using {@link #msgTarget} to determine how to
766 * display the messages and applying {@link #invalidCls} to the field's UI element.
768 * **Note**: this method does not cause the Field's {@link #validate} or {@link #isValid} methods to return `false`
769 * if the value does _pass_ validation. So simply marking a Field as invalid will not prevent submission of forms
770 * submitted with the {@link Ext.form.action.Submit#clientValidation} option set.
772 * @param {String/String[]} errors The validation message(s) to display.
774 markInvalid : function(errors) {
775 // Save the message and fire the 'invalid' event
777 oldMsg = me.getActiveError();
778 me.setActiveErrors(Ext.Array.from(errors));
779 if (oldMsg !== me.getActiveError()) {
780 me.doComponentLayout();
785 * Clear any invalid styles/messages for this field.
787 * **Note**: this method does not cause the Field's {@link #validate} or {@link #isValid} methods to return `true`
788 * if the value does not _pass_ validation. So simply clearing a field's errors will not necessarily allow
789 * submission of forms submitted with the {@link Ext.form.action.Submit#clientValidation} option set.
791 clearInvalid : function() {
792 // Clear the message and fire the 'valid' event
794 hadError = me.hasActiveError();
795 me.unsetActiveError();
797 me.doComponentLayout();
802 * @private Overrides the method from the Ext.form.Labelable mixin to also add the invalidCls to the inputEl,
803 * as that is required for proper styling in IE with nested fields (due to lack of child selector)
805 renderActiveError: function() {
807 hasError = me.hasActiveError();
809 // Add/remove invalid class
810 me.inputEl[hasError ? 'addCls' : 'removeCls'](me.invalidCls + '-field');
812 me.mixins.labelable.renderActiveError.call(me);
816 getActionEl: function() {
817 return this.inputEl || this.el;