Roo/form/ComboBoxArray.js
[roojs1] / Roo / form / Field.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11  
12 /**
13  * @class Roo.form.Field
14  * @extends Roo.BoxComponent
15  * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
16  * @constructor
17  * Creates a new Field
18  * @param {Object} config Configuration options
19  */
20 Roo.form.Field = function(config){
21     Roo.form.Field.superclass.constructor.call(this, config);
22 };
23
24 Roo.extend(Roo.form.Field, Roo.BoxComponent,  {
25     /**
26      * @cfg {String} fieldLabel Label to use when rendering a form.
27      */
28        /**
29      * @cfg {String} qtip Mouse over tip
30      */
31      
32     /**
33      * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
34      */
35     invalidClass : "x-form-invalid",
36     /**
37      * @cfg {String} invalidText The error text to use when marking a field invalid and no message is provided (defaults to "The value in this field is invalid")
38      */
39     invalidText : "The value in this field is invalid",
40     /**
41      * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
42      */
43     focusClass : "x-form-focus",
44     /**
45      * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
46       automatic validation (defaults to "keyup").
47      */
48     validationEvent : "keyup",
49     /**
50      * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
51      */
52     validateOnBlur : true,
53     /**
54      * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
55      */
56     validationDelay : 250,
57     /**
58      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
59      * {tag: "input", type: "text", size: "20", autocomplete: "off"})
60      */
61     defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "off"},
62     /**
63      * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field")
64      */
65     fieldClass : "x-form-field",
66     /**
67      * @cfg {String} msgTarget The location where error text should display.  Should be one of the following values (defaults to 'qtip'):
68      *<pre>
69 Value         Description
70 -----------   ----------------------------------------------------------------------
71 qtip          Display a quick tip when the user hovers over the field
72 title         Display a default browser title attribute popup
73 under         Add a block div beneath the field containing the error text
74 side          Add an error icon to the right of the field with a popup on hover
75 [element id]  Add the error text directly to the innerHTML of the specified element
76 </pre>
77      */
78     msgTarget : 'qtip',
79     /**
80      * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field (defaults to 'normal').
81      */
82     msgFx : 'normal',
83
84     /**
85      * @cfg {Boolean} readOnly True to mark the field as readOnly in HTML (defaults to false) -- Note: this only sets the element's readOnly DOM attribute.
86      */
87     readOnly : false,
88
89     /**
90      * @cfg {Boolean} disabled True to disable the field (defaults to false).
91      */
92     disabled : false,
93
94     /**
95      * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password (defaults to "text").
96      */
97     inputType : undefined,
98     
99     /**
100      * @cfg {Number} tabIndex The tabIndex for this field. Note this only applies to fields that are rendered, not those which are built via applyTo (defaults to undefined).
101          */
102         tabIndex : undefined,
103         
104     // private
105     isFormField : true,
106
107     // private
108     hasFocus : false,
109     /**
110      * @property {Roo.Element} fieldEl
111      * Element Containing the rendered Field (with label etc.)
112      */
113     /**
114      * @cfg {Mixed} value A value to initialize this field with.
115      */
116     value : undefined,
117
118     /**
119      * @cfg {String} name The field's HTML name attribute.
120      */
121     /**
122      * @cfg {String} cls A CSS class to apply to the field's underlying element.
123      */
124
125         // private ??
126         initComponent : function(){
127         Roo.form.Field.superclass.initComponent.call(this);
128         this.addEvents({
129             /**
130              * @event focus
131              * Fires when this field receives input focus.
132              * @param {Roo.form.Field} this
133              */
134             focus : true,
135             /**
136              * @event blur
137              * Fires when this field loses input focus.
138              * @param {Roo.form.Field} this
139              */
140             blur : true,
141             /**
142              * @event specialkey
143              * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
144              * {@link Roo.EventObject#getKey} to determine which key was pressed.
145              * @param {Roo.form.Field} this
146              * @param {Roo.EventObject} e The event object
147              */
148             specialkey : true,
149             /**
150              * @event change
151              * Fires just before the field blurs if the field value has changed.
152              * @param {Roo.form.Field} this
153              * @param {Mixed} newValue The new value
154              * @param {Mixed} oldValue The original value
155              */
156             change : true,
157             /**
158              * @event invalid
159              * Fires after the field has been marked as invalid.
160              * @param {Roo.form.Field} this
161              * @param {String} msg The validation message
162              */
163             invalid : true,
164             /**
165              * @event valid
166              * Fires after the field has been validated with no errors.
167              * @param {Roo.form.Field} this
168              */
169             valid : true,
170              /**
171              * @event keyup
172              * Fires after the key up
173              * @param {Roo.form.Field} this
174              * @param {Roo.EventObject}  e The event Object
175              */
176             keyup : true
177         });
178     },
179
180     /**
181      * Returns the name attribute of the field if available
182      * @return {String} name The field name
183      */
184     getName: function(){
185          return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
186     },
187
188     // private
189     onRender : function(ct, position){
190         Roo.form.Field.superclass.onRender.call(this, ct, position);
191         if(!this.el){
192             var cfg = this.getAutoCreate();
193             if(!cfg.name){
194                 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
195             }
196             if (!cfg.name.length) {
197                 delete cfg.name;
198             }
199             if(this.inputType){
200                 cfg.type = this.inputType;
201             }
202             this.el = ct.createChild(cfg, position);
203         }
204         var type = this.el.dom.type;
205         if(type){
206             if(type == 'password'){
207                 type = 'text';
208             }
209             this.el.addClass('x-form-'+type);
210         }
211         if(this.readOnly){
212             this.el.dom.readOnly = true;
213         }
214         if(this.tabIndex !== undefined){
215             this.el.dom.setAttribute('tabIndex', this.tabIndex);
216         }
217
218         this.el.addClass([this.fieldClass, this.cls]);
219         this.initValue();
220     },
221
222     /**
223      * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b>
224      * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element
225      * @return {Roo.form.Field} this
226      */
227     applyTo : function(target){
228         this.allowDomMove = false;
229         this.el = Roo.get(target);
230         this.render(this.el.dom.parentNode);
231         return this;
232     },
233
234     // private
235     initValue : function(){
236         if(this.value !== undefined){
237             this.setValue(this.value);
238         }else if(this.el.dom.value.length > 0){
239             this.setValue(this.el.dom.value);
240         }
241     },
242
243     /**
244      * Returns true if this field has been changed since it was originally loaded and is not disabled.
245      */
246     isDirty : function() {
247         if(this.disabled) {
248             return false;
249         }
250         return String(this.getValue()) !== String(this.originalValue);
251     },
252
253     // private
254     afterRender : function(){
255         Roo.form.Field.superclass.afterRender.call(this);
256         this.initEvents();
257     },
258
259     // private
260     fireKey : function(e){
261         //Roo.log('field ' + e.getKey());
262         if(e.isNavKeyPress()){
263             this.fireEvent("specialkey", this, e);
264         }
265     },
266
267     /**
268      * Resets the current field value to the originally loaded value and clears any validation messages
269      */
270     reset : function(){
271         this.setValue(this.resetValue);
272         this.clearInvalid();
273     },
274
275     // private
276     initEvents : function(){
277         // safari killled keypress - so keydown is now used..
278         this.el.on("keydown" , this.fireKey,  this);
279         this.el.on("focus", this.onFocus,  this);
280         this.el.on("blur", this.onBlur,  this);
281         this.el.relayEvent('keyup', this);
282
283         // reference to original value for reset
284         this.originalValue = this.getValue();
285         this.resetValue =  this.getValue();
286     },
287
288     // private
289     onFocus : function(){
290         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
291             this.el.addClass(this.focusClass);
292         }
293         if(!this.hasFocus){
294             this.hasFocus = true;
295             this.startValue = this.getValue();
296             this.fireEvent("focus", this);
297         }
298     },
299
300     beforeBlur : Roo.emptyFn,
301
302     // private
303     onBlur : function(){
304         this.beforeBlur();
305         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
306             this.el.removeClass(this.focusClass);
307         }
308         this.hasFocus = false;
309         if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
310             this.validate();
311         }
312         var v = this.getValue();
313         if(String(v) !== String(this.startValue)){
314             this.fireEvent('change', this, v, this.startValue);
315         }
316         this.fireEvent("blur", this);
317     },
318
319     /**
320      * Returns whether or not the field value is currently valid
321      * @param {Boolean} preventMark True to disable marking the field invalid
322      * @return {Boolean} True if the value is valid, else false
323      */
324     isValid : function(preventMark){
325         if(this.disabled){
326             return true;
327         }
328         var restore = this.preventMark;
329         this.preventMark = preventMark === true;
330         var v = this.validateValue(this.processValue(this.getRawValue()));
331         this.preventMark = restore;
332         return v;
333     },
334
335     /**
336      * Validates the field value
337      * @return {Boolean} True if the value is valid, else false
338      */
339     validate : function(){
340         if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
341             this.clearInvalid();
342             return true;
343         }
344         return false;
345     },
346
347     processValue : function(value){
348         return value;
349     },
350
351     // private
352     // Subclasses should provide the validation implementation by overriding this
353     validateValue : function(value){
354         return true;
355     },
356
357     /**
358      * Mark this field as invalid
359      * @param {String} msg The validation message
360      */
361     markInvalid : function(msg){
362         if(!this.rendered || this.preventMark){ // not rendered
363             return;
364         }
365         
366         var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
367         
368         obj.el.addClass(this.invalidClass);
369         msg = msg || this.invalidText;
370         switch(this.msgTarget){
371             case 'qtip':
372                 obj.el.dom.qtip = msg;
373                 obj.el.dom.qclass = 'x-form-invalid-tip';
374                 if(Roo.QuickTips){ // fix for floating editors interacting with DND
375                     Roo.QuickTips.enable();
376                 }
377                 break;
378             case 'title':
379                 this.el.dom.title = msg;
380                 break;
381             case 'under':
382                 if(!this.errorEl){
383                     var elp = this.el.findParent('.x-form-element', 5, true);
384                     this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
385                     this.errorEl.setWidth(elp.getWidth(true)-20);
386                 }
387                 this.errorEl.update(msg);
388                 Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
389                 break;
390             case 'side':
391                 if(!this.errorIcon){
392                     var elp = this.el.findParent('.x-form-element', 5, true);
393                     this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
394                 }
395                 this.alignErrorIcon();
396                 this.errorIcon.dom.qtip = msg;
397                 this.errorIcon.dom.qclass = 'x-form-invalid-tip';
398                 this.errorIcon.show();
399                 this.on('resize', this.alignErrorIcon, this);
400                 break;
401             default:
402                 var t = Roo.getDom(this.msgTarget);
403                 t.innerHTML = msg;
404                 t.style.display = this.msgDisplay;
405                 break;
406         }
407         this.fireEvent('invalid', this, msg);
408     },
409
410     // private
411     alignErrorIcon : function(){
412         this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
413     },
414
415     /**
416      * Clear any invalid styles/messages for this field
417      */
418     clearInvalid : function(){
419         if(!this.rendered || this.preventMark){ // not rendered
420             return;
421         }
422         var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
423         
424         obj.el.removeClass(this.invalidClass);
425         switch(this.msgTarget){
426             case 'qtip':
427                 obj.el.dom.qtip = '';
428                 break;
429             case 'title':
430                 this.el.dom.title = '';
431                 break;
432             case 'under':
433                 if(this.errorEl){
434                     Roo.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
435                 }
436                 break;
437             case 'side':
438                 if(this.errorIcon){
439                     this.errorIcon.dom.qtip = '';
440                     this.errorIcon.hide();
441                     this.un('resize', this.alignErrorIcon, this);
442                 }
443                 break;
444             default:
445                 var t = Roo.getDom(this.msgTarget);
446                 t.innerHTML = '';
447                 t.style.display = 'none';
448                 break;
449         }
450         this.fireEvent('valid', this);
451     },
452
453     /**
454      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
455      * @return {Mixed} value The field value
456      */
457     getRawValue : function(){
458         var v = this.el.getValue();
459         
460         return v;
461     },
462
463     /**
464      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
465      * @return {Mixed} value The field value
466      */
467     getValue : function(){
468         var v = this.el.getValue();
469          
470         return v;
471     },
472
473     /**
474      * Sets the underlying DOM field's value directly, bypassing validation.  To set the value with validation see {@link #setValue}.
475      * @param {Mixed} value The value to set
476      */
477     setRawValue : function(v){
478         return this.el.dom.value = (v === null || v === undefined ? '' : v);
479     },
480
481     /**
482      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
483      * @param {Mixed} value The value to set
484      */
485     setValue : function(v){
486         this.value = v;
487         if(this.rendered){
488             this.el.dom.value = (v === null || v === undefined ? '' : v);
489              this.validate();
490         }
491     },
492
493     adjustSize : function(w, h){
494         var s = Roo.form.Field.superclass.adjustSize.call(this, w, h);
495         s.width = this.adjustWidth(this.el.dom.tagName, s.width);
496         return s;
497     },
498
499     adjustWidth : function(tag, w){
500         tag = tag.toLowerCase();
501         if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
502             if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
503                 if(tag == 'input'){
504                     return w + 2;
505                 }
506                 if(tag == 'textarea'){
507                     return w-2;
508                 }
509             }else if(Roo.isOpera){
510                 if(tag == 'input'){
511                     return w + 2;
512                 }
513                 if(tag == 'textarea'){
514                     return w-2;
515                 }
516             }
517         }
518         return w;
519     }
520 });
521
522
523 // anything other than normal should be considered experimental
524 Roo.form.Field.msgFx = {
525     normal : {
526         show: function(msgEl, f){
527             msgEl.setDisplayed('block');
528         },
529
530         hide : function(msgEl, f){
531             msgEl.setDisplayed(false).update('');
532         }
533     },
534
535     slide : {
536         show: function(msgEl, f){
537             msgEl.slideIn('t', {stopFx:true});
538         },
539
540         hide : function(msgEl, f){
541             msgEl.slideOut('t', {stopFx:true,useDisplay:true});
542         }
543     },
544
545     slideRight : {
546         show: function(msgEl, f){
547             msgEl.fixDisplay();
548             msgEl.alignTo(f.el, 'tl-tr');
549             msgEl.slideIn('l', {stopFx:true});
550         },
551
552         hide : function(msgEl, f){
553             msgEl.slideOut('l', {stopFx:true,useDisplay:true});
554         }
555     }
556 };