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