roojs-ui.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 = this.name || this.id;
195             }
196             if(this.inputType){
197                 cfg.type = this.inputType;
198             }
199             this.el = ct.createChild(cfg, position);
200         }
201         var type = this.el.dom.type;
202         if(type){
203             if(type == 'password'){
204                 type = 'text';
205             }
206             this.el.addClass('x-form-'+type);
207         }
208         if(this.readOnly){
209             this.el.dom.readOnly = true;
210         }
211         if(this.tabIndex !== undefined){
212             this.el.dom.setAttribute('tabIndex', this.tabIndex);
213         }
214
215         this.el.addClass([this.fieldClass, this.cls]);
216         this.initValue();
217     },
218
219     /**
220      * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b>
221      * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element
222      * @return {Roo.form.Field} this
223      */
224     applyTo : function(target){
225         this.allowDomMove = false;
226         this.el = Roo.get(target);
227         this.render(this.el.dom.parentNode);
228         return this;
229     },
230
231     // private
232     initValue : function(){
233         if(this.value !== undefined){
234             this.setValue(this.value);
235         }else if(this.el.dom.value.length > 0){
236             this.setValue(this.el.dom.value);
237         }
238     },
239
240     /**
241      * Returns true if this field has been changed since it was originally loaded and is not disabled.
242      */
243     isDirty : function() {
244         if(this.disabled) {
245             return false;
246         }
247         return String(this.getValue()) !== String(this.originalValue);
248     },
249
250     // private
251     afterRender : function(){
252         Roo.form.Field.superclass.afterRender.call(this);
253         this.initEvents();
254     },
255
256     // private
257     fireKey : function(e){
258         //Roo.log('field ' + e.getKey());
259         if(e.isNavKeyPress()){
260             this.fireEvent("specialkey", this, e);
261         }
262     },
263
264     /**
265      * Resets the current field value to the originally loaded value and clears any validation messages
266      */
267     reset : function(){
268         this.setValue(this.originalValue);
269         this.clearInvalid();
270     },
271
272     // private
273     initEvents : function(){
274         // safari killled keypress - so keydown is now used..
275         this.el.on("keydown" , this.fireKey,  this);
276         this.el.on("focus", this.onFocus,  this);
277         this.el.on("blur", this.onBlur,  this);
278         this.el.relayEvent('keyup', this);
279
280         // reference to original value for reset
281         this.originalValue = this.getValue();
282     },
283
284     // private
285     onFocus : function(){
286         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
287             this.el.addClass(this.focusClass);
288         }
289         if(!this.hasFocus){
290             this.hasFocus = true;
291             this.startValue = this.getValue();
292             this.fireEvent("focus", this);
293         }
294     },
295
296     beforeBlur : Roo.emptyFn,
297
298     // private
299     onBlur : function(){
300         this.beforeBlur();
301         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
302             this.el.removeClass(this.focusClass);
303         }
304         this.hasFocus = false;
305         if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
306             this.validate();
307         }
308         var v = this.getValue();
309         if(String(v) !== String(this.startValue)){
310             this.fireEvent('change', this, v, this.startValue);
311         }
312         this.fireEvent("blur", this);
313     },
314
315     /**
316      * Returns whether or not the field value is currently valid
317      * @param {Boolean} preventMark True to disable marking the field invalid
318      * @return {Boolean} True if the value is valid, else false
319      */
320     isValid : function(preventMark){
321         if(this.disabled){
322             return true;
323         }
324         var restore = this.preventMark;
325         this.preventMark = preventMark === true;
326         var v = this.validateValue(this.processValue(this.getRawValue()));
327         this.preventMark = restore;
328         return v;
329     },
330
331     /**
332      * Validates the field value
333      * @return {Boolean} True if the value is valid, else false
334      */
335     validate : function(){
336         if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
337             this.clearInvalid();
338             return true;
339         }
340         return false;
341     },
342
343     processValue : function(value){
344         return value;
345     },
346
347     // private
348     // Subclasses should provide the validation implementation by overriding this
349     validateValue : function(value){
350         return true;
351     },
352
353     /**
354      * Mark this field as invalid
355      * @param {String} msg The validation message
356      */
357     markInvalid : function(msg){
358         if(!this.rendered || this.preventMark){ // not rendered
359             return;
360         }
361         this.el.addClass(this.invalidClass);
362         msg = msg || this.invalidText;
363         switch(this.msgTarget){
364             case 'qtip':
365                 this.el.dom.qtip = msg;
366                 this.el.dom.qclass = 'x-form-invalid-tip';
367                 if(Roo.QuickTips){ // fix for floating editors interacting with DND
368                     Roo.QuickTips.enable();
369                 }
370                 break;
371             case 'title':
372                 this.el.dom.title = msg;
373                 break;
374             case 'under':
375                 if(!this.errorEl){
376                     var elp = this.el.findParent('.x-form-element', 5, true);
377                     this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
378                     this.errorEl.setWidth(elp.getWidth(true)-20);
379                 }
380                 this.errorEl.update(msg);
381                 Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
382                 break;
383             case 'side':
384                 if(!this.errorIcon){
385                     var elp = this.el.findParent('.x-form-element', 5, true);
386                     this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
387                 }
388                 this.alignErrorIcon();
389                 this.errorIcon.dom.qtip = msg;
390                 this.errorIcon.dom.qclass = 'x-form-invalid-tip';
391                 this.errorIcon.show();
392                 this.on('resize', this.alignErrorIcon, this);
393                 break;
394             default:
395                 var t = Roo.getDom(this.msgTarget);
396                 t.innerHTML = msg;
397                 t.style.display = this.msgDisplay;
398                 break;
399         }
400         this.fireEvent('invalid', this, msg);
401     },
402
403     // private
404     alignErrorIcon : function(){
405         this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
406     },
407
408     /**
409      * Clear any invalid styles/messages for this field
410      */
411     clearInvalid : function(){
412         if(!this.rendered || this.preventMark){ // not rendered
413             return;
414         }
415         this.el.removeClass(this.invalidClass);
416         switch(this.msgTarget){
417             case 'qtip':
418                 this.el.dom.qtip = '';
419                 break;
420             case 'title':
421                 this.el.dom.title = '';
422                 break;
423             case 'under':
424                 if(this.errorEl){
425                     Roo.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
426                 }
427                 break;
428             case 'side':
429                 if(this.errorIcon){
430                     this.errorIcon.dom.qtip = '';
431                     this.errorIcon.hide();
432                     this.un('resize', this.alignErrorIcon, this);
433                 }
434                 break;
435             default:
436                 var t = Roo.getDom(this.msgTarget);
437                 t.innerHTML = '';
438                 t.style.display = 'none';
439                 break;
440         }
441         this.fireEvent('valid', this);
442     },
443
444     /**
445      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
446      * @return {Mixed} value The field value
447      */
448     getRawValue : function(){
449         var v = this.el.getValue();
450         if(v === this.emptyText){
451             v = '';
452         }
453         return v;
454     },
455
456     /**
457      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
458      * @return {Mixed} value The field value
459      */
460     getValue : function(){
461         var v = this.el.getValue();
462         if(v === this.emptyText || v === undefined){
463             v = '';
464         }
465         return v;
466     },
467
468     /**
469      * Sets the underlying DOM field's value directly, bypassing validation.  To set the value with validation see {@link #setValue}.
470      * @param {Mixed} value The value to set
471      */
472     setRawValue : function(v){
473         return this.el.dom.value = (v === null || v === undefined ? '' : v);
474     },
475
476     /**
477      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
478      * @param {Mixed} value The value to set
479      */
480     setValue : function(v){
481         this.value = v;
482         if(this.rendered){
483             this.el.dom.value = (v === null || v === undefined ? '' : v);
484              this.validate();
485         }
486     },
487
488     adjustSize : function(w, h){
489         var s = Roo.form.Field.superclass.adjustSize.call(this, w, h);
490         s.width = this.adjustWidth(this.el.dom.tagName, s.width);
491         return s;
492     },
493
494     adjustWidth : function(tag, w){
495         tag = tag.toLowerCase();
496         if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
497             if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
498                 if(tag == 'input'){
499                     return w + 2;
500                 }
501                 if(tag = 'textarea'){
502                     return w-2;
503                 }
504             }else if(Roo.isOpera){
505                 if(tag == 'input'){
506                     return w + 2;
507                 }
508                 if(tag = 'textarea'){
509                     return w-2;
510                 }
511             }
512         }
513         return w;
514     }
515 });
516
517
518 // anything other than normal should be considered experimental
519 Roo.form.Field.msgFx = {
520     normal : {
521         show: function(msgEl, f){
522             msgEl.setDisplayed('block');
523         },
524
525         hide : function(msgEl, f){
526             msgEl.setDisplayed(false).update('');
527         }
528     },
529
530     slide : {
531         show: function(msgEl, f){
532             msgEl.slideIn('t', {stopFx:true});
533         },
534
535         hide : function(msgEl, f){
536             msgEl.slideOut('t', {stopFx:true,useDisplay:true});
537         }
538     },
539
540     slideRight : {
541         show: function(msgEl, f){
542             msgEl.fixDisplay();
543             msgEl.alignTo(f.el, 'tl-tr');
544             msgEl.slideIn('l', {stopFx:true});
545         },
546
547         hide : function(msgEl, f){
548             msgEl.slideOut('l', {stopFx:true,useDisplay:true});
549         }
550     }
551 };