Upgrade to ExtJS 3.1.0 - Released 12/16/2009
[extjs.git] / src / widgets / form / Field.js
1 /*!
2  * Ext JS Library 3.1.0
3  * Copyright(c) 2006-2009 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.form.Field
9  * @extends Ext.BoxComponent
10  * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
11  * @constructor
12  * Creates a new Field
13  * @param {Object} config Configuration options
14  * @xtype field
15  */
16 Ext.form.Field = Ext.extend(Ext.BoxComponent,  {
17     /**
18      * <p>The label Element associated with this Field. <b>Only available after this Field has been rendered by a
19      * {@link form Ext.layout.FormLayout} layout manager.</b></p>
20      * @type Ext.Element
21      * @property label
22      */
23     /**
24      * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password, file (defaults
25      * to 'text'). The types 'file' and 'password' must be used to render those field types currently -- there are
26      * no separate Ext components for those. Note that if you use <tt>inputType:'file'</tt>, {@link #emptyText}
27      * is not supported and should be avoided.
28      */
29     /**
30      * @cfg {Number} tabIndex The tabIndex for this field. Note this only applies to fields that are rendered,
31      * not those which are built via applyTo (defaults to undefined).
32      */
33     /**
34      * @cfg {Mixed} value A value to initialize this field with (defaults to undefined).
35      */
36     /**
37      * @cfg {String} name The field's HTML name attribute (defaults to '').
38      * <b>Note</b>: this property must be set if this field is to be automatically included with
39      * {@link Ext.form.BasicForm#submit form submit()}.
40      */
41     /**
42      * @cfg {String} cls A custom CSS class to apply to the field's underlying element (defaults to '').
43      */
44
45     /**
46      * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to 'x-form-invalid')
47      */
48     invalidClass : 'x-form-invalid',
49     /**
50      * @cfg {String} invalidText The error text to use when marking a field invalid and no message is provided
51      * (defaults to 'The value in this field is invalid')
52      */
53     invalidText : 'The value in this field is invalid',
54     /**
55      * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to 'x-form-focus')
56      */
57     focusClass : 'x-form-focus',
58     /**
59      * @cfg {Boolean} preventMark
60      * <tt>true</tt> to disable {@link #markInvalid marking the field invalid}.
61      * Defaults to <tt>false</tt>.
62      */
63     /**
64      * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
65       automatic validation (defaults to 'keyup').
66      */
67     validationEvent : 'keyup',
68     /**
69      * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
70      */
71     validateOnBlur : true,
72     /**
73      * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation
74      * is initiated (defaults to 250)
75      */
76     validationDelay : 250,
77     /**
78      * @cfg {String/Object} autoCreate <p>A {@link Ext.DomHelper DomHelper} element spec, or true for a default
79      * element spec. Used to create the {@link Ext.Component#getEl Element} which will encapsulate this Component.
80      * See <tt>{@link Ext.Component#autoEl autoEl}</tt> for details.  Defaults to:</p>
81      * <pre><code>{tag: 'input', type: 'text', size: '20', autocomplete: 'off'}</code></pre>
82      */
83     defaultAutoCreate : {tag: 'input', type: 'text', size: '20', autocomplete: 'off'},
84     /**
85      * @cfg {String} fieldClass The default CSS class for the field (defaults to 'x-form-field')
86      */
87     fieldClass : 'x-form-field',
88     /**
89      * @cfg {String} msgTarget<p>The location where the message text set through {@link #markInvalid} should display. 
90      * Must be one of the following values:</p>
91      * <div class="mdetail-params"><ul>
92      * <li><code>qtip</code> Display a quick tip containing the message when the user hovers over the field. This is the default.
93      * <div class="subdesc"><b>{@link Ext.QuickTips#init Ext.QuickTips.init} must have been called for this setting to work.</b></div</li>
94      * <li><code>title</code> Display the message in a default browser title attribute popup.</li>
95      * <li><code>under</code> Add a block div beneath the field containing the error message.</li>
96      * <li><code>side</code> Add an error icon to the right of the field, displaying the message in a popup on hover.</li>
97      * <li><code>[element id]</code> Add the error message directly to the innerHTML of the specified element.</li>
98      * </ul></div>
99      */
100     msgTarget : 'qtip',
101     /**
102      * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field
103      * (defaults to 'normal').
104      */
105     msgFx : 'normal',
106     /**
107      * @cfg {Boolean} readOnly <tt>true</tt> to mark the field as readOnly in HTML
108      * (defaults to <tt>false</tt>).
109      * <br><p><b>Note</b>: this only sets the element's readOnly DOM attribute.
110      * Setting <code>readOnly=true</code>, for example, will not disable triggering a
111      * ComboBox or DateField; it gives you the option of forcing the user to choose
112      * via the trigger without typing in the text box. To hide the trigger use
113      * <code>{@link Ext.form.TriggerField#hideTrigger hideTrigger}</code>.</p>
114      */
115     readOnly : false,
116     /**
117      * @cfg {Boolean} disabled True to disable the field (defaults to false).
118      * <p>Be aware that conformant with the <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.12.1">HTML specification</a>,
119      * disabled Fields will not be {@link Ext.form.BasicForm#submit submitted}.</p>
120      */
121     disabled : false,
122     /**
123      * @cfg {Boolean} submitValue False to clear the name attribute on the field so that it is not submitted during a form post.
124      * Defaults to <tt>true</tt>.
125      */
126     submitValue: true,
127
128     // private
129     isFormField : true,
130
131     // private
132     msgDisplay: '',
133
134     // private
135     hasFocus : false,
136
137     // private
138     initComponent : function(){
139         Ext.form.Field.superclass.initComponent.call(this);
140         this.addEvents(
141             /**
142              * @event focus
143              * Fires when this field receives input focus.
144              * @param {Ext.form.Field} this
145              */
146             'focus',
147             /**
148              * @event blur
149              * Fires when this field loses input focus.
150              * @param {Ext.form.Field} this
151              */
152             'blur',
153             /**
154              * @event specialkey
155              * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.
156              * To handle other keys see {@link Ext.Panel#keys} or {@link Ext.KeyMap}.
157              * You can check {@link Ext.EventObject#getKey} to determine which key was pressed.
158              * For example: <pre><code>
159 var form = new Ext.form.FormPanel({
160     ...
161     items: [{
162             fieldLabel: 'Field 1',
163             name: 'field1',
164             allowBlank: false
165         },{
166             fieldLabel: 'Field 2',
167             name: 'field2',
168             listeners: {
169                 specialkey: function(field, e){
170                     // e.HOME, e.END, e.PAGE_UP, e.PAGE_DOWN,
171                     // e.TAB, e.ESC, arrow keys: e.LEFT, e.RIGHT, e.UP, e.DOWN
172                     if (e.{@link Ext.EventObject#getKey getKey()} == e.ENTER) {
173                         var form = field.ownerCt.getForm();
174                         form.submit();
175                     }
176                 }
177             }
178         }
179     ],
180     ...
181 });
182              * </code></pre>
183              * @param {Ext.form.Field} this
184              * @param {Ext.EventObject} e The event object
185              */
186             'specialkey',
187             /**
188              * @event change
189              * Fires just before the field blurs if the field value has changed.
190              * @param {Ext.form.Field} this
191              * @param {Mixed} newValue The new value
192              * @param {Mixed} oldValue The original value
193              */
194             'change',
195             /**
196              * @event invalid
197              * Fires after the field has been marked as invalid.
198              * @param {Ext.form.Field} this
199              * @param {String} msg The validation message
200              */
201             'invalid',
202             /**
203              * @event valid
204              * Fires after the field has been validated with no errors.
205              * @param {Ext.form.Field} this
206              */
207             'valid'
208         );
209     },
210
211     /**
212      * Returns the {@link Ext.form.Field#name name} or {@link Ext.form.ComboBox#hiddenName hiddenName}
213      * attribute of the field if available.
214      * @return {String} name The field {@link Ext.form.Field#name name} or {@link Ext.form.ComboBox#hiddenName hiddenName}
215      */
216     getName : function(){
217         return this.rendered && this.el.dom.name ? this.el.dom.name : this.name || this.id || '';
218     },
219
220     // private
221     onRender : function(ct, position){
222         if(!this.el){
223             var cfg = this.getAutoCreate();
224
225             if(!cfg.name){
226                 cfg.name = this.name || this.id;
227             }
228             if(this.inputType){
229                 cfg.type = this.inputType;
230             }
231             this.autoEl = cfg;
232         }
233         Ext.form.Field.superclass.onRender.call(this, ct, position);
234         if(this.submitValue === false){
235             this.el.dom.removeAttribute('name');
236         }
237         var type = this.el.dom.type;
238         if(type){
239             if(type == 'password'){
240                 type = 'text';
241             }
242             this.el.addClass('x-form-'+type);
243         }
244         if(this.readOnly){
245             this.setReadOnly(true);
246         }
247         if(this.tabIndex !== undefined){
248             this.el.dom.setAttribute('tabIndex', this.tabIndex);
249         }
250
251         this.el.addClass([this.fieldClass, this.cls]);
252     },
253
254     // private
255     getItemCt : function(){
256         return this.itemCt;
257     },
258
259     // private
260     initValue : function(){
261         if(this.value !== undefined){
262             this.setValue(this.value);
263         }else if(!Ext.isEmpty(this.el.dom.value) && this.el.dom.value != this.emptyText){
264             this.setValue(this.el.dom.value);
265         }
266         /**
267          * The original value of the field as configured in the {@link #value} configuration, or
268          * as loaded by the last form load operation if the form's {@link Ext.form.BasicForm#trackResetOnLoad trackResetOnLoad}
269          * setting is <code>true</code>.
270          * @type mixed
271          * @property originalValue
272          */
273         this.originalValue = this.getValue();
274     },
275
276     /**
277      * <p>Returns true if the value of this Field has been changed from its original value.
278      * Will return false if the field is disabled or has not been rendered yet.</p>
279      * <p>Note that if the owning {@link Ext.form.BasicForm form} was configured with
280      * {@link Ext.form.BasicForm}.{@link Ext.form.BasicForm#trackResetOnLoad trackResetOnLoad}
281      * then the <i>original value</i> is updated when the values are loaded by
282      * {@link Ext.form.BasicForm}.{@link Ext.form.BasicForm#setValues setValues}.</p>
283      * @return {Boolean} True if this field has been changed from its original value (and
284      * is not disabled), false otherwise.
285      */
286     isDirty : function() {
287         if(this.disabled || !this.rendered) {
288             return false;
289         }
290         return String(this.getValue()) !== String(this.originalValue);
291     },
292     
293     /**
294      * Sets the read only state of this field.
295      * @param {Boolean} readOnly Whether the field should be read only.
296      */
297     setReadOnly : function(readOnly){
298         if(this.rendered){
299             this.el.dom.readOnly = readOnly;
300         }
301         this.readOnly = readOnly;
302     },
303
304     // private
305     afterRender : function(){
306         Ext.form.Field.superclass.afterRender.call(this);
307         this.initEvents();
308         this.initValue();
309     },
310
311     // private
312     fireKey : function(e){
313         if(e.isSpecialKey()){
314             this.fireEvent('specialkey', this, e);
315         }
316     },
317
318     /**
319      * Resets the current field value to the originally loaded value and clears any validation messages.
320      * See {@link Ext.form.BasicForm}.{@link Ext.form.BasicForm#trackResetOnLoad trackResetOnLoad}
321      */
322     reset : function(){
323         this.setValue(this.originalValue);
324         this.clearInvalid();
325     },
326
327     // private
328     initEvents : function(){
329         this.mon(this.el, Ext.EventManager.useKeydown ? 'keydown' : 'keypress', this.fireKey,  this);
330         this.mon(this.el, 'focus', this.onFocus, this);
331
332         // standardise buffer across all browsers + OS-es for consistent event order.
333         // (the 10ms buffer for Editors fixes a weird FF/Win editor issue when changing OS window focus)
334         this.mon(this.el, 'blur', this.onBlur, this, this.inEditor ? {buffer:10} : null);
335     },
336
337     // private
338     preFocus: Ext.emptyFn,
339
340     // private
341     onFocus : function(){
342         this.preFocus();
343         if(this.focusClass){
344             this.el.addClass(this.focusClass);
345         }
346         if(!this.hasFocus){
347             this.hasFocus = true;
348             /**
349              * <p>The value that the Field had at the time it was last focused. This is the value that is passed
350              * to the {@link #change} event which is fired if the value has been changed when the Field is blurred.</p>
351              * <p><b>This will be undefined until the Field has been visited.</b> Compare {@link #originalValue}.</p>
352              * @type mixed
353              * @property startValue
354              */
355             this.startValue = this.getValue();
356             this.fireEvent('focus', this);
357         }
358     },
359
360     // private
361     beforeBlur : Ext.emptyFn,
362
363     // private
364     onBlur : function(){
365         this.beforeBlur();
366         if(this.focusClass){
367             this.el.removeClass(this.focusClass);
368         }
369         this.hasFocus = false;
370         if(this.validationEvent !== false && (this.validateOnBlur || this.validationEvent == 'blur')){
371             this.validate();
372         }
373         var v = this.getValue();
374         if(String(v) !== String(this.startValue)){
375             this.fireEvent('change', this, v, this.startValue);
376         }
377         this.fireEvent('blur', this);
378         this.postBlur();
379     },
380
381     // private
382     postBlur : Ext.emptyFn,
383
384     /**
385      * Returns whether or not the field value is currently valid by
386      * {@link #validateValue validating} the {@link #processValue processed value}
387      * of the field. <b>Note</b>: {@link #disabled} fields are ignored.
388      * @param {Boolean} preventMark True to disable marking the field invalid
389      * @return {Boolean} True if the value is valid, else false
390      */
391     isValid : function(preventMark){
392         if(this.disabled){
393             return true;
394         }
395         var restore = this.preventMark;
396         this.preventMark = preventMark === true;
397         var v = this.validateValue(this.processValue(this.getRawValue()));
398         this.preventMark = restore;
399         return v;
400     },
401
402     /**
403      * Validates the field value
404      * @return {Boolean} True if the value is valid, else false
405      */
406     validate : function(){
407         if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
408             this.clearInvalid();
409             return true;
410         }
411         return false;
412     },
413
414     /**
415      * This method should only be overridden if necessary to prepare raw values
416      * for validation (see {@link #validate} and {@link #isValid}).  This method
417      * is expected to return the processed value for the field which will
418      * be used for validation (see validateValue method).
419      * @param {Mixed} value
420      */
421     processValue : function(value){
422         return value;
423     },
424
425     /**
426      * @private
427      * Subclasses should provide the validation implementation by overriding this
428      * @param {Mixed} value
429      */
430     validateValue : function(value){
431         return true;
432     },
433     
434     /**
435      * Gets the active error message for this field.
436      * @return {String} Returns the active error message on the field, if there is no error, an empty string is returned.
437      */
438     getActiveError : function(){
439         return this.activeError || '';    
440     },
441
442     /**
443      * <p>Display an error message associated with this field, using {@link #msgTarget} to determine how to
444      * display the message and applying {@link #invalidClass} to the field's UI element.</p>
445      * <p><b>Note</b>: this method does not cause the Field's {@link #validate} method to return <code>false</code>
446      * if the value does <i>pass</i> validation. So simply marking a Field as invalid will not prevent
447      * submission of forms submitted with the {@link Ext.form.Action.Submit#clientValidation} option set.</p>
448      * {@link #isValid invalid}.
449      * @param {String} msg (optional) The validation message (defaults to {@link #invalidText})
450      */
451     markInvalid : function(msg){
452         if(!this.rendered || this.preventMark){ // not rendered
453             return;
454         }
455         msg = msg || this.invalidText;
456
457         var mt = this.getMessageHandler();
458         if(mt){
459             mt.mark(this, msg);
460         }else if(this.msgTarget){
461             this.el.addClass(this.invalidClass);
462             var t = Ext.getDom(this.msgTarget);
463             if(t){
464                 t.innerHTML = msg;
465                 t.style.display = this.msgDisplay;
466             }
467         }
468         this.activeError = msg;
469         this.fireEvent('invalid', this, msg);
470     },
471
472     /**
473      * Clear any invalid styles/messages for this field
474      */
475     clearInvalid : function(){
476         if(!this.rendered || this.preventMark){ // not rendered
477             return;
478         }
479         this.el.removeClass(this.invalidClass);
480         var mt = this.getMessageHandler();
481         if(mt){
482             mt.clear(this);
483         }else if(this.msgTarget){
484             this.el.removeClass(this.invalidClass);
485             var t = Ext.getDom(this.msgTarget);
486             if(t){
487                 t.innerHTML = '';
488                 t.style.display = 'none';
489             }
490         }
491         delete this.activeError;
492         this.fireEvent('valid', this);
493     },
494
495     // private
496     getMessageHandler : function(){
497         return Ext.form.MessageTargets[this.msgTarget];
498     },
499
500     // private
501     getErrorCt : function(){
502         return this.el.findParent('.x-form-element', 5, true) || // use form element wrap if available
503             this.el.findParent('.x-form-field-wrap', 5, true);   // else direct field wrap
504     },
505
506     // private
507     alignErrorIcon : function(){
508         this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
509     },
510
511     /**
512      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
513      * @return {Mixed} value The field value
514      */
515     getRawValue : function(){
516         var v = this.rendered ? this.el.getValue() : Ext.value(this.value, '');
517         if(v === this.emptyText){
518             v = '';
519         }
520         return v;
521     },
522
523     /**
524      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
525      * @return {Mixed} value The field value
526      */
527     getValue : function(){
528         if(!this.rendered) {
529             return this.value;
530         }
531         var v = this.el.getValue();
532         if(v === this.emptyText || v === undefined){
533             v = '';
534         }
535         return v;
536     },
537
538     /**
539      * Sets the underlying DOM field's value directly, bypassing validation.  To set the value with validation see {@link #setValue}.
540      * @param {Mixed} value The value to set
541      * @return {Mixed} value The field value that is set
542      */
543     setRawValue : function(v){
544         return this.rendered ? (this.el.dom.value = (Ext.isEmpty(v) ? '' : v)) : '';
545     },
546
547     /**
548      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
549      * @param {Mixed} value The value to set
550      * @return {Ext.form.Field} this
551      */
552     setValue : function(v){
553         this.value = v;
554         if(this.rendered){
555             this.el.dom.value = (Ext.isEmpty(v) ? '' : v);
556             this.validate();
557         }
558         return this;
559     },
560
561     // private, does not work for all fields
562     append : function(v){
563          this.setValue([this.getValue(), v].join(''));
564     }
565
566     /**
567      * @cfg {Boolean} autoWidth @hide
568      */
569     /**
570      * @cfg {Boolean} autoHeight @hide
571      */
572
573     /**
574      * @cfg {String} autoEl @hide
575      */
576 });
577
578
579 Ext.form.MessageTargets = {
580     'qtip' : {
581         mark: function(field, msg){
582             field.el.addClass(field.invalidClass);
583             field.el.dom.qtip = msg;
584             field.el.dom.qclass = 'x-form-invalid-tip';
585             if(Ext.QuickTips){ // fix for floating editors interacting with DND
586                 Ext.QuickTips.enable();
587             }
588         },
589         clear: function(field){
590             field.el.removeClass(field.invalidClass);
591             field.el.dom.qtip = '';
592         }
593     },
594     'title' : {
595         mark: function(field, msg){
596             field.el.addClass(field.invalidClass);
597             field.el.dom.title = msg;
598         },
599         clear: function(field){
600             field.el.dom.title = '';
601         }
602     },
603     'under' : {
604         mark: function(field, msg){
605             field.el.addClass(field.invalidClass);
606             if(!field.errorEl){
607                 var elp = field.getErrorCt();
608                 if(!elp){ // field has no container el
609                     field.el.dom.title = msg;
610                     return;
611                 }
612                 field.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
613                 field.errorEl.setWidth(elp.getWidth(true)-20);
614             }
615             field.errorEl.update(msg);
616             Ext.form.Field.msgFx[field.msgFx].show(field.errorEl, field);
617         },
618         clear: function(field){
619             field.el.removeClass(field.invalidClass);
620             if(field.errorEl){
621                 Ext.form.Field.msgFx[field.msgFx].hide(field.errorEl, field);
622             }else{
623                 field.el.dom.title = '';
624             }
625         }
626     },
627     'side' : {
628         mark: function(field, msg){
629             field.el.addClass(field.invalidClass);
630             if(!field.errorIcon){
631                 var elp = field.getErrorCt();
632                 if(!elp){ // field has no container el
633                     field.el.dom.title = msg;
634                     return;
635                 }
636                 field.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
637             }
638             field.alignErrorIcon();
639             field.errorIcon.dom.qtip = msg;
640             field.errorIcon.dom.qclass = 'x-form-invalid-tip';
641             field.errorIcon.show();
642             field.on('resize', field.alignErrorIcon, field);
643         },
644         clear: function(field){
645             field.el.removeClass(field.invalidClass);
646             if(field.errorIcon){
647                 field.errorIcon.dom.qtip = '';
648                 field.errorIcon.hide();
649                 field.un('resize', field.alignErrorIcon, field);
650             }else{
651                 field.el.dom.title = '';
652             }
653         }
654     }
655 };
656
657 // anything other than normal should be considered experimental
658 Ext.form.Field.msgFx = {
659     normal : {
660         show: function(msgEl, f){
661             msgEl.setDisplayed('block');
662         },
663
664         hide : function(msgEl, f){
665             msgEl.setDisplayed(false).update('');
666         }
667     },
668
669     slide : {
670         show: function(msgEl, f){
671             msgEl.slideIn('t', {stopFx:true});
672         },
673
674         hide : function(msgEl, f){
675             msgEl.slideOut('t', {stopFx:true,useDisplay:true});
676         }
677     },
678
679     slideRight : {
680         show: function(msgEl, f){
681             msgEl.fixDisplay();
682             msgEl.alignTo(f.el, 'tl-tr');
683             msgEl.slideIn('l', {stopFx:true});
684         },
685
686         hide : function(msgEl, f){
687             msgEl.slideOut('l', {stopFx:true,useDisplay:true});
688         }
689     }
690 };
691 Ext.reg('field', Ext.form.Field);