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