allow string based values for comboboxarray
[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: "new-password"},
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     // private
125     loadedValue : false,
126      
127      
128         // private ??
129         initComponent : function(){
130         Roo.form.Field.superclass.initComponent.call(this);
131         this.addEvents({
132             /**
133              * @event focus
134              * Fires when this field receives input focus.
135              * @param {Roo.form.Field} this
136              */
137             focus : true,
138             /**
139              * @event blur
140              * Fires when this field loses input focus.
141              * @param {Roo.form.Field} this
142              */
143             blur : true,
144             /**
145              * @event specialkey
146              * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
147              * {@link Roo.EventObject#getKey} to determine which key was pressed.
148              * @param {Roo.form.Field} this
149              * @param {Roo.EventObject} e The event object
150              */
151             specialkey : true,
152             /**
153              * @event change
154              * Fires just before the field blurs if the field value has changed.
155              * @param {Roo.form.Field} this
156              * @param {Mixed} newValue The new value
157              * @param {Mixed} oldValue The original value
158              */
159             change : true,
160             /**
161              * @event invalid
162              * Fires after the field has been marked as invalid.
163              * @param {Roo.form.Field} this
164              * @param {String} msg The validation message
165              */
166             invalid : true,
167             /**
168              * @event valid
169              * Fires after the field has been validated with no errors.
170              * @param {Roo.form.Field} this
171              */
172             valid : true,
173              /**
174              * @event keyup
175              * Fires after the key up
176              * @param {Roo.form.Field} this
177              * @param {Roo.EventObject}  e The event Object
178              */
179             keyup : true
180         });
181     },
182
183     /**
184      * Returns the name attribute of the field if available
185      * @return {String} name The field name
186      */
187     getName: function(){
188          return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
189     },
190
191     // private
192     onRender : function(ct, position){
193         Roo.form.Field.superclass.onRender.call(this, ct, position);
194         if(!this.el){
195             var cfg = this.getAutoCreate();
196             if(!cfg.name){
197                 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
198             }
199             if (!cfg.name.length) {
200                 delete cfg.name;
201             }
202             if(this.inputType){
203                 cfg.type = this.inputType;
204             }
205             this.el = ct.createChild(cfg, position);
206         }
207         var type = this.el.dom.type;
208         if(type){
209             if(type == 'password'){
210                 type = 'text';
211             }
212             this.el.addClass('x-form-'+type);
213         }
214         if(this.readOnly){
215             this.el.dom.readOnly = true;
216         }
217         if(this.tabIndex !== undefined){
218             this.el.dom.setAttribute('tabIndex', this.tabIndex);
219         }
220
221         this.el.addClass([this.fieldClass, this.cls]);
222         this.initValue();
223     },
224
225     /**
226      * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b>
227      * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element
228      * @return {Roo.form.Field} this
229      */
230     applyTo : function(target){
231         this.allowDomMove = false;
232         this.el = Roo.get(target);
233         this.render(this.el.dom.parentNode);
234         return this;
235     },
236
237     // private
238     initValue : function(){
239         if(this.value !== undefined){
240             this.setValue(this.value);
241         }else if(this.el.dom.value.length > 0){
242             this.setValue(this.el.dom.value);
243         }
244     },
245
246     /**
247      * Returns true if this field has been changed since it was originally loaded and is not disabled.
248      * DEPRICATED  - it never worked well - use hasChanged/resetHasChanged.
249      */
250     isDirty : function() {
251         if(this.disabled) {
252             return false;
253         }
254         return String(this.getValue()) !== String(this.originalValue);
255     },
256
257     /**
258      * stores the current value in loadedValue
259      */
260     resetHasChanged : function()
261     {
262         this.loadedValue = String(this.getValue());
263     },
264     /**
265      * checks the current value against the 'loaded' value.
266      * Note - will return false if 'resetHasChanged' has not been called first.
267      */
268     hasChanged : function()
269     {
270         if(this.disabled || this.readOnly) {
271             return false;
272         }
273         return this.loadedValue !== false && String(this.getValue()) !== this.loadedValue;
274     },
275     
276     
277     
278     // private
279     afterRender : function(){
280         Roo.form.Field.superclass.afterRender.call(this);
281         this.initEvents();
282     },
283
284     // private
285     fireKey : function(e){
286         //Roo.log('field ' + e.getKey());
287         if(e.isNavKeyPress()){
288             this.fireEvent("specialkey", this, e);
289         }
290     },
291
292     /**
293      * Resets the current field value to the originally loaded value and clears any validation messages
294      */
295     reset : function(){
296         this.setValue(this.resetValue);
297         this.originalValue = this.getValue();
298         this.clearInvalid();
299     },
300
301     // private
302     initEvents : function(){
303         // safari killled keypress - so keydown is now used..
304         this.el.on("keydown" , this.fireKey,  this);
305         this.el.on("focus", this.onFocus,  this);
306         this.el.on("blur", this.onBlur,  this);
307         this.el.relayEvent('keyup', this);
308
309         // reference to original value for reset
310         this.originalValue = this.getValue();
311         this.resetValue =  this.getValue();
312     },
313
314     // private
315     onFocus : function(){
316         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
317             this.el.addClass(this.focusClass);
318         }
319         if(!this.hasFocus){
320             this.hasFocus = true;
321             this.startValue = this.getValue();
322             this.fireEvent("focus", this);
323         }
324     },
325
326     beforeBlur : Roo.emptyFn,
327
328     // private
329     onBlur : function(){
330         this.beforeBlur();
331         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
332             this.el.removeClass(this.focusClass);
333         }
334         this.hasFocus = false;
335         if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
336             this.validate();
337         }
338         var v = this.getValue();
339         if(String(v) !== String(this.startValue)){
340             this.fireEvent('change', this, v, this.startValue);
341         }
342         this.fireEvent("blur", this);
343     },
344
345     /**
346      * Returns whether or not the field value is currently valid
347      * @param {Boolean} preventMark True to disable marking the field invalid
348      * @return {Boolean} True if the value is valid, else false
349      */
350     isValid : function(preventMark){
351         if(this.disabled){
352             return true;
353         }
354         var restore = this.preventMark;
355         this.preventMark = preventMark === true;
356         var v = this.validateValue(this.processValue(this.getRawValue()));
357         this.preventMark = restore;
358         return v;
359     },
360
361     /**
362      * Validates the field value
363      * @return {Boolean} True if the value is valid, else false
364      */
365     validate : function(){
366         if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
367             this.clearInvalid();
368             return true;
369         }
370         return false;
371     },
372
373     processValue : function(value){
374         return value;
375     },
376
377     // private
378     // Subclasses should provide the validation implementation by overriding this
379     validateValue : function(value){
380         return true;
381     },
382
383     /**
384      * Mark this field as invalid
385      * @param {String} msg The validation message
386      */
387     markInvalid : function(msg){
388         if(!this.rendered || this.preventMark){ // not rendered
389             return;
390         }
391         
392         var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
393         
394         obj.el.addClass(this.invalidClass);
395         msg = msg || this.invalidText;
396         switch(this.msgTarget){
397             case 'qtip':
398                 obj.el.dom.qtip = msg;
399                 obj.el.dom.qclass = 'x-form-invalid-tip';
400                 if(Roo.QuickTips){ // fix for floating editors interacting with DND
401                     Roo.QuickTips.enable();
402                 }
403                 break;
404             case 'title':
405                 this.el.dom.title = msg;
406                 break;
407             case 'under':
408                 if(!this.errorEl){
409                     var elp = this.el.findParent('.x-form-element', 5, true);
410                     this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
411                     this.errorEl.setWidth(elp.getWidth(true)-20);
412                 }
413                 this.errorEl.update(msg);
414                 Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
415                 break;
416             case 'side':
417                 if(!this.errorIcon){
418                     var elp = this.el.findParent('.x-form-element', 5, true);
419                     this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
420                 }
421                 this.alignErrorIcon();
422                 this.errorIcon.dom.qtip = msg;
423                 this.errorIcon.dom.qclass = 'x-form-invalid-tip';
424                 this.errorIcon.show();
425                 this.on('resize', this.alignErrorIcon, this);
426                 break;
427             default:
428                 var t = Roo.getDom(this.msgTarget);
429                 t.innerHTML = msg;
430                 t.style.display = this.msgDisplay;
431                 break;
432         }
433         this.fireEvent('invalid', this, msg);
434     },
435
436     // private
437     alignErrorIcon : function(){
438         this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
439     },
440
441     /**
442      * Clear any invalid styles/messages for this field
443      */
444     clearInvalid : function(){
445         if(!this.rendered || this.preventMark){ // not rendered
446             return;
447         }
448         var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
449         
450         obj.el.removeClass(this.invalidClass);
451         switch(this.msgTarget){
452             case 'qtip':
453                 obj.el.dom.qtip = '';
454                 break;
455             case 'title':
456                 this.el.dom.title = '';
457                 break;
458             case 'under':
459                 if(this.errorEl){
460                     Roo.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
461                 }
462                 break;
463             case 'side':
464                 if(this.errorIcon){
465                     this.errorIcon.dom.qtip = '';
466                     this.errorIcon.hide();
467                     this.un('resize', this.alignErrorIcon, this);
468                 }
469                 break;
470             default:
471                 var t = Roo.getDom(this.msgTarget);
472                 t.innerHTML = '';
473                 t.style.display = 'none';
474                 break;
475         }
476         this.fireEvent('valid', this);
477     },
478
479     /**
480      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
481      * @return {Mixed} value The field value
482      */
483     getRawValue : function(){
484         var v = this.el.getValue();
485         
486         return v;
487     },
488
489     /**
490      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
491      * @return {Mixed} value The field value
492      */
493     getValue : function(){
494         var v = this.el.getValue();
495          
496         return v;
497     },
498
499     /**
500      * Sets the underlying DOM field's value directly, bypassing validation.  To set the value with validation see {@link #setValue}.
501      * @param {Mixed} value The value to set
502      */
503     setRawValue : function(v){
504         return this.el.dom.value = (v === null || v === undefined ? '' : v);
505     },
506
507     /**
508      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
509      * @param {Mixed} value The value to set
510      */
511     setValue : function(v){
512         this.value = v;
513         if(this.rendered){
514             this.el.dom.value = (v === null || v === undefined ? '' : v);
515              this.validate();
516         }
517     },
518
519     adjustSize : function(w, h){
520         var s = Roo.form.Field.superclass.adjustSize.call(this, w, h);
521         s.width = this.adjustWidth(this.el.dom.tagName, s.width);
522         return s;
523     },
524
525     adjustWidth : function(tag, w){
526         tag = tag.toLowerCase();
527         if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
528             if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
529                 if(tag == 'input'){
530                     return w + 2;
531                 }
532                 if(tag == 'textarea'){
533                     return w-2;
534                 }
535             }else if(Roo.isOpera){
536                 if(tag == 'input'){
537                     return w + 2;
538                 }
539                 if(tag == 'textarea'){
540                     return w-2;
541                 }
542             }
543         }
544         return w;
545     }
546 });
547
548
549 // anything other than normal should be considered experimental
550 Roo.form.Field.msgFx = {
551     normal : {
552         show: function(msgEl, f){
553             msgEl.setDisplayed('block');
554         },
555
556         hide : function(msgEl, f){
557             msgEl.setDisplayed(false).update('');
558         }
559     },
560
561     slide : {
562         show: function(msgEl, f){
563             msgEl.slideIn('t', {stopFx:true});
564         },
565
566         hide : function(msgEl, f){
567             msgEl.slideOut('t', {stopFx:true,useDisplay:true});
568         }
569     },
570
571     slideRight : {
572         show: function(msgEl, f){
573             msgEl.fixDisplay();
574             msgEl.alignTo(f.el, 'tl-tr');
575             msgEl.slideIn('l', {stopFx:true});
576         },
577
578         hide : function(msgEl, f){
579             msgEl.slideOut('l', {stopFx:true,useDisplay:true});
580         }
581     }
582 };